DR. AJAY KUMAR PATHAK
ASSISTANT PROFESSOR
READ ALL THE NOTES CHAPTER WISE
SUBJECT NAME:- MJ–12 (Th):- WEB PROGRAMMING
FOR B. Sc. IT.
SEM 6 F.Y.U.G.P.
SUBJECT : MJ–12 (Th): WEB PROGRAMMING
(To be selected by the students from)
UNIT 5 (UNIT NAME):- JAVE SCRIPT
Objective: The objective of the course is to enable students to
· The objective of this course is to provide students with a comprehensive understanding of network security concepts and techniques. The course aims to develop students' skills in identifying network vulnerabilities, implementing security measures, and ensuring the confidentiality, integrity, and availability of networked systems.
Learning Outcome:- After completion of this course, a student will be able to–
· Understand the principles and concepts of network security.
· Identify potential security threats and vulnerabilities in networked systems.
· Implement security measures to protect network infrastructure.
· Apply encryption and authentication techniques to secure network communication.
· Analyze and respond to security incidents in networked environments
Semester Examination and Distribution of Marks
INTERNAL MARKS :- 25 (NO PRACTICAL IN THE MJ 12 (WEB PROGRAMMING)
End Semester Examination (ESE) : 75 Marks
SYLLABUS OF JAVA SCRIPT
UNIT- 5 :- JAVA SCRIPT
WHAT IS JAVASCRIPT?
JavaScript has no connectivity with Java
programming language. Be cure full java programming language is different and
JavaScript language is different. It was introduced in the year 1995 for adding
programs to the webpages in the Netscape Navigator browser. Since then, it has
been adopted by all other graphical web browsers. With JavaScript, users can
build modern web applications to interact directly without reloading the page
every time. The traditional website uses js to provide several forms of
interactivity and simplicity.
JavaScript is a programming language that developers use to make interactive
webpages. From refreshing social media
feeds to displaying animations and interactive maps, JavaScript functions can
improve a website's user experience. As a client-side scripting language, it is
one of the core technologies of the World Wide Web. For example, when browsing
the internet, anytime you see an image container, a click-to-show dropdown
menu, or dynamically changing element colors on a webpage, you see the effects
of JavaScript.
HISTORY OF JAVASCRIPT
Brendan Eich first developed
JavaScript, a computer language, in about ten days in May 1995. The language,
formerly known as Mocha, later modified to LiveScript, and is now known simply
as JavaScript, was created to be used on the client-side of websites, enabling
the addition of dynamic and interactive components to static HTML texts.
JavaScript was initially
implemented in Netscape Navigator, which was the most popular browser at the
time. The language was quickly adopted by Microsoft for use in Internet
Explorer. Due to its simplicity of usage and the fact that it was the only
client-side scripting language available at the time, JavaScript quickly gained
popularity among web developers.
HOW DOES JAVASCRIPT
WORK?
All programming languages work
by translating English-like syntax into machine code, which the operating
system then runs. JavaScript is broadly categorized as a scripting language, or
an interpreted language. JavaScript code is interpreted—that is, directly
translated into underlying machine language code by a JavaScript engine. With
other programming languages, a compiler compiles the entire code into machine
code in a separate step. Thus, all scripting languages are programming
languages, but not all programming languages are scripting languages.
TYPE OF JAVASCRIPT
(1) CLIENT-SIDE
JAVASCRIPT
Client-side JavaScript refers to
the way JavaScript works in your browser. In this case, the JavaScript engine
is inside the browser code. All major web browsers come with their own built-in
JavaScript engines.
Web application developers
write JavaScript code with different functions associated with various events,
such as a mouse click or mouse hover. These functions make changes to the HTML
and CSS.
Overview of how client-side
JavaScript works:
1. The browser loads a webpage when you visit
it.
2. During loading, the browser converts the
page and all its elements, such as buttons, labels, and dropdown boxes, into a
data structure called the Document Object Model (DOM).
3. The browser's JavaScript engine converts the
JavaScript code into bytecode. This code is an intermediary between the
JavaScript syntax and the machine.
4. Different events, such as a mouse click on a
button, trigger the execution of the associated JavaScript code block. The
engine then interprets the bytecode and makes changes to the DOM.
5. The browser displays the new DOM.
(2) SERVER-SIDE
JAVASCRIPT
Server-side JavaScript refers
to the use of the coding language in back-end server logic. In this case, the
JavaScript engine sits directly on the server. A server-side JavaScript
function can access the database, perform different logical operations, and
respond to various events triggered by the server's operating system. The
primary advantage of server-side scripting is that you can highly customize the
website response based on your requirements, your access rights, and the
information requests from the website.
WHAT ARE THE BENEFITS /
ADVANTAGES OF JAVASCRIPT?:-
(1) Easily learn and use : JavaScript's syntax was inspired by the
Java programming language and is easy to learn and code. Developers use
JavaScript in almost every website and mobile app for client-side scripting.
Node.js has also gained significant popularity for backend coding in the last
decade. Many major streaming and video platforms have been coded in Node.js.
(2) Gain platform independence
: Unlike with
other programming languages, you can insert JavaScript into any webpage and use
it with many other web development frameworks and languages. Once you have
written it, you can run JavaScript code on any machine. Thus, JavaScript makes
application development platform independent.
(3) Reduce server load : You can use JavaScript to reduce server
load and network congestion because it can run logical operations and do a lot
of the server's work on the client itself. For example, consider the process of
filling out a registration form. JavaScript quickly checks if you have entered
a 10-digit number for the mobile phone field. If these requests were sent to
the server, your page would reload for every error, making the registration
process very slow and tedious.
(4) Improve the user
interface: JavaScript
creates elegant websites that make it convenient to find and process complex
information. Developers apply JavaScript to extend functionality and
readability and to make website user interaction more efficient.
(5) Support concurrency : JavaScript can run several different
sets of instructions in parallel. On the backend, Node.js can handle and
process highly scaled-up server responses without consuming the same amount of
bandwidth.
(1). Web Applications : Various JavaScript frameworks are used
for developing and building robust web applications. In an application like
Google Maps, if users want to explore a map, all they have to do is click and
drag the mouse to get a detailed view. This is powered by JavaScript, which
interacts with the browser without communicating with the servers.
2) Presentations: A very popular application of
JavaScript is to create interactive presentations as websites. The RevealJs and
BespokeJs libraries can be used to generate web-based slide decks using HTML.
The RevealJs helps create interactive slide decks with transitions styles,
themes, and slide backgrounds in all CSS color formats.
(3). Web Development : JavaScript is a scripting language used
to develop web pages. Developed in Netscape, JS allows developers to create a
dynamic and interactive web page to interact with visitors and execute complex
actions. It also enables users to load content into a document without
reloading the entire page. Most websites use JavaScript for validation and to
support external applications, including PDF documents, widgets, flash
applications.
(4) Server Applications : JavaScript is also used to write
server-side software through Node.js open-source runtime environment.
Developers can write, test and debug code for fast and accessible network
applications. JavaScript helps to generate content and manage HTTP requests.
Top companies like Walmart, PayPal, Uber, GoDaddy, and many more have adopted
Node.js for server infrastructure.
(5).Web Servers: Node.js allows developers to use
JavaScript to create a web server. Node.js being event-driven, it moves to the
next call without waiting for the response of the previous call.
(6). Games : Creating games on the web is another
important one among applications of JavaScript. The combination of JavaScript
and HTML5 plays a major role in games development using JS.
(7). Art : A recent feature of HTML5 in JavaScript
is the canvas element, which allows drawing 2D and 3D graphics easily on a web
page
(8).Mobile Apps : One of the most powerful applications
of JavaScript is to create apps for non-web contexts, meaning for things, not
on the Internet. With the use of mobile devices at an all-time high,
(9) Flying Robots : We can use JavaScript to program a
flying robot. With the Node.js ecosystem.
(10). Smartwatch Apps: Pebble.js is a JavaScript framework by
Pebble, allowing developers to create applications for Pebble watches using
JavaScript.
FROM HERE, NOW HOW TO START JAVA SCRIPTING PROGRAM
HOW DO YOU ADD JAVASCRIPT TO
YOUR PAGE?:-
JavaScript is applied to your HTML page
in a similar manner to CSS. Whereas CSS uses <link> elements to apply
external stylesheets and <style> elements to apply internal stylesheets
to HTML, JavaScript only needs one friend in the world of HTML — the
<script> element. Let's learn how this works.
(1) To open Notepad++ OR Notepad
(2) Now write the code.
(3) BELOW IS THE CODE
<DOCTYPE html>
<html>
<head>
<title>How to write first
Javascript Program in Notepad editor</title>
</head>
<body>
<!-- JAVA SCRIPT COMMENTS LINE, JAVA
SCRIPTING ALWAYS START<script> tag and close with </script> tag
FROM HERE JAVA SCRIPTING BELOW - - >
<script>
document.write("This is my
first Javascript Program in Notepad");
</script>
//JAVA SCRIPT COMMENTS LINE, STARTING
FROM HERE JAVA SCRIPTING
ABOVE //
</body>
</html>
(4) After writing the above JavaScript
code, you need to save it.
(5) Type file name
“myFirstJavascriptProgram” OR ANY FILENAME and Save as type: select extension
“*.html; *.htm;” option and then click on the save button.
(6). Now Run the program with Browser.
HOW MANY WAYS WE CAN WRITES
THE CODE IN JAVASCRIPT (WE CAN USE THREE WAYS OFJAVASCRIPT)
(1) Inline JavaScript
(2) Internal JavaScript
(3) External JavaScript
STEPS (NOTE) : ALL FILES MUST BE SAVED
IN ONLY SAME FOLDER LIKE, HTML FILE, CSS FILE JAVASCRIPT FILE
OR inline JavaScript means JavaScript
placed directly in the HTML file, without in a .JS file.
This is extremely advantageous as it can
save the web browser round trips to the server. This is because it no longer
requires an external file to download from the server-side.
<!DOCTYPE html>
<html>
<head>
<title>Inline
JavaScript EXAMPLE </title>
</head>
<body>
<!— OR BELOW CODE ALSO -- >
<h1onClick
=”alert (‘HELLO’)”>HELLO WORLD </h1><!—When we are writing a code
in the HTML tag (HERE h1 IS A HTML TAG) that is called inline JavaScript,
through the ALERT FUNCTION will show a popup menu, when we click on that menu
will get a message HELLO WORLD -- >
</body>
</html>
Internal JavaScript code is code that's
placed anywhere within the web page between the HTML tags . Many web developers
choose to place their JavaScript code before the tag.
When JavaScript was written within the
section using element then it is called as internal JavaScript.
If the number of lines of Javascript is
relatively small, a web page with internal Javascript loads faster than pages
that must reference external code. This is because, as the web browser loads
the page and encounters the reference to the external code, it must make a
separate request to the web server to fetch the code.
(NOTE:
WE CAN WRITE CODE INSIDE THE BODY TAG OR WE CAN ALSO WRITE THE CODE IN
THE HEAD TAG PROGRAM WILL EXECUTE)
<!DOCTYPE html>
<html>
<head>
<title>EXAMPLE OF INTERNAL
JAVASCRIPT</title>
</head>
<body>
<!—WHEN WE WILL WRITE THE CODE IN THE
OPEN AND CLOSE <SCRIPT></SCRIPT> THE IS CALLED INTERNAL JAVASCRIPT
-- >
<script
type="text/javascript">
document.write("This is Internal Javascript Example.!!!");
</script>
</body>
</html>
THE END
(3) EXTERNAL JAVASCRIPT:
JavaScript code placed in a file
separate from the HTML code is called external JavaScript. External JavaScript
code is written and used in the same way as internal JavaScript. The file
should have the ".js" extension. Writing java script in a separate
file with extension .js is called as external JavaScript.
It is recommended to embed all
JavaScript files into a single file. It increases the speed of the webpage.
To use an external script, put the name
of the script file in the src (source) attribute of a <script> tag:
(1) It separates HTML and code
(2) It helps in the reusability of code
in more than one HTML file
(3) It makes HTML and JavaScript easier
to read and maintain
(4) The length of the code reduces as
only we need to specify the location of the js file.
(5) Designers can work along with coders
parallel without code conflicts
(6) Reserved JavaScript files can speed
up page loads
(1) The browser has to make an extra
http request to get the js code.
(2) Code can be downloaded using the url
of the js file.
(3) We need to check each file that
depends on the commonly created external javascript file.
(4) If it is a few lines of code, then
better to implement the internal javascript code.
(5) A small change to a common js file
may cause unexpected results .
THIS IS JAVASCRIPT FILE
FILE NAME IS externaljava.js
Now program
(1. Open note pad
2. Type the following code in note pad
and save as externaljava.js or any file_name_with_extention.js)
function msg(){
alert("Hello I AM AJAY KUMAR PATHAK, I AM
USING EXTERNAL JAVASCRIPT FOR B.SC IT SEM 4");
}
<html>
<head>
<!—FROM HERE I AM USING EXTERNAL
JAVASCRIPT -- >
<script
type="text/javascript"
src="externaljava.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button"
value="click" onclick="msg()"/>
</form>
</body>
</html
Now run the program with browser
OUTPUT
WHAT IS VARIABLES IN
JAVASCRIPT
(NOTE: ALL RULES OF VARIABLES
C, C++, JAVA ETC. ARE APPLIED IN JAVASCRIPT)
VARIABLES :-
A variable is a container (storage area) to hold data. Variable means
anything that can vary. JavaScript Variables are the building blocks of any
programming language. In JavaScript, variables can be used to store reusable
values. The values of the variables are store by using the assignment
operator(“=”).
There are some basic rules to declare a
variable in JavaScript:
1) These
are case-sensitive
2) Can
only begin with a letter, underscore(“_”) or “$” symbol
3) It
can contain letters, numbers, underscore, or “$” symbol
4) A
variable name cannot be a reserved keyword.
(1) varkeyword :- var keyword is used to declare
variables since JavaScript was created. It is confusing and error-prone
(something bad) when using variables declared using var. varis used in the
older versions of JavaScript
For example, var x;
var name=”ajay kumar pathak”; //assigned
string value
var num = 100; //assigned numeric value
var isActive = true; //assigned boolean
value
COPY THE VALUES
var num1 = 100;
var num2 = num1;
Multiple Variables
Multiple Variables
MULTIPLE VARIABLES IN A SINGLE STATEMENT
var test1 = 12,
test2= 14,
test3 = 16
var name = "ajay", num =
“100”, isActive = “true”;
SAME VALUE CAN ASSIGN BUT 2nd VALUE WILL
DISPLAY
var num = 100;
var num = 200; //Ok
For example, let y;
let name = "ajay"; //assigned
string value
let num = 100; //assigned numeric value
COPY THE VALUES
let num1 = 100;
let num2 = num1;
Multiple Variables:-
let name = "Steve", num = 100,
isActive = true;
SAME VALUE CAN NOT ASSIGN
let num = 100;
let num = 200; //syntax error
Example: Constant Variables
const num = 100;
num = 200; //error
name = "ajay”;
person.name = "pathak";
alert(person.name); //pathak
VARIABLE SCOPE
In JavaScript, a variable can be
declared either in the global scope or the local scope.
EXAMPLE: - Global and Local Variable
let greet = "Hello " // global
variable
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}
alert(greet);//can access global
variable
alert(msg); //error: can't access local
variable
(2) Local Variables :- Variables declared inside the function
are called local variables of that function. They can only be accessed in the
function where they are declared but not outside.
Variables can be defined using let
keyword. Variables defined without let or var keyword become global variables.
Variables should be initialized before
accessing it. Unassigned variable has value undefined.
JavaScript is a loosely-typed language,
so a variable can store any type value.
Loosely Typed VariableS:-
let myvariable = 1; // numeric value
myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
<html>
<head>
<title> USE OF VARIABLES
</title>
<script>
myname =’ajay kumar’;
document.write(“MY NAME IS =”,myname) //
OUT PUT WILL DISPLAY AJAY KUMAR//
let myname=ajay kumar pathak’;
let myname=”ajay kumar”; // here error
will display because let will not support //
document.write((“MY NAME IS =”,myname)
// OUT PUT WILL notDISPLAY AJAY KUMAR
because there is a error //
let myname=’ajay kumar pathak’;
myname=’ajay kumar’; // here error will
not display because let will support this type of declaration //
document.write((“MY NAME IS =”,myname)
// OUT PUT WILL notDISPLAY AJAY KUMAR
because there is a error //
const myname=”ajay kumar pathak”;
myname=”ajay kumar”; // here error will
not display , output will come//
document.write(myname)
const myname=”ajay kumar pathak”;
const
myname=”ajay kumar”;// here error will
display , output will not come because on same variable name we con not
use two time const//
document.write((“MY NAME IS =”,myname)
</head>
<body>
</body>
</html>
THE END
WHAT ARE THE OPERATORS IN
JAVASCRIPT
JavaScript includes operators same as
other languages.
An operator performs some operation on
single or multiple operands (data value) and produces a result. JavaScript
operators are symbols that are used to perform operations on operands.
For example:
The following types of operators
available in JavaScript
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator
(1) Arithmetic Operators : -Arithmetic operators are used to perform
mathematical operations between numeric operands
|
Operator |
Description |
|
+ |
Adds two numeric operands. |
|
- |
Subtract right operand from left operand |
|
* |
Multiply two numeric operands. |
|
/ |
Divide left operand by right operand. |
|
% |
Modulus operator. Returns remainder of two
operands. |
|
++ |
Increment operator. Increase operand value
by one. |
|
-- |
Decrement operator. Decrease value by one. |
|
Example: Post and Pre
Increment/Decrement |
|
let x = 5; |
|
x++; //post-increment, x will be 5
here and 6 in the next line |
|
++x; //pre-increment, x will be 7
here |
|
x--; //post-decrement, x will be 7
here and 6 in the next line |
|
--x; //pre-decrement, x will be 5 here |
(2) Comparison Operators : JavaScript provides comparison operators
that compare two operands and return a Boolean value true or false.
|
Operators |
Description |
|
= = |
Compares the equality of two operands
without considering type. |
|
= = = |
Compares equality of two operands with
type. Example <p id="p1">a = = c
returns </p> <p id="p2">a = = = c
returns </p> <p id="p3">a = = x
returns </p> <p id="p4">a != b
returns </p> <script> let a = 5, b = 10, c = "5",
x = a; document.getElementById("p1").innerHTML
+= a == c; document.getElementById("p2").innerHTML
+= a === c; document.getElementById("p3").innerHTML
+= a == x; document.getElementById("p4").innerHTML
+= a != b; </script> OUTPUT let a = 5, b = 10, c = "5",
x = a; a = = c returns true a = = = c returns false a = = x returns true a != b returns true |
|
!= |
Compares inequality of two operands. |
|
> |
Returns a boolean value true if the
left-side value is greater than the right-side value; otherwise, returns
false. |
|
< |
Returns a boolean value true if the
left-side value is less than the right-side value; otherwise, returns false. |
|
>= |
Returns a boolean value true if the
left-side value is greater than or equal to the right-side value; otherwise,
returns false. |
|
<= |
Returns a boolean value true if the
left-side value is less than or equal to the right-side value; otherwise,
returns false. |
(3) Logical Operators
: In JavaScript, the logical operators
are used to combine two or more conditions. JavaScript provides the following
logical operators.
|
Operator |
Description |
|
&& |
&& is known as AND operator.
It checks whether two operands are non-zero or not (0, false, undefined, null
or "" are considered as zero). It returns 1 if they are non-zero;
otherwise, returns 0. |
|
|| |
|| is known as OR operator. It checks
whether any one of the two operands is non-zero or not (0, false, undefined,
null or "" is considered as zero). It returns 1 if any one of of
them is non-zero; otherwise, returns 0. |
|
! |
! is known as NOT operator. It
reverses the boolean result of the operand (or
condition). !false returns true,
and !true returns false. |
(4 ) Assignment Operators: JavaScript provides the assignment
operators to assign values to the variables.There are also compound assignment
operators that are shorthand for the operations listed in the following table:
|
Assignment operators |
Description |
|
= |
Assigns right operand value to the left
operand. |
|
+= |
Sums up left and right operand values
and assigns the result to the left operand. |
|
-= |
Subtract right operand value from the
left operand value and assigns the result to the left operand. |
|
*= |
Multiply left and right operand values
and assigns the result to the left operand. |
|
/= |
Divide left operand value by right
operand value and assign the result to the left operand. |
|
%= |
Get the modulus of left operand divide
by right operand and assign resulted modulus to the left operand. |
|
Exponentiation assignment |
x **= f() |
x = x ** f() |
|
Left shift assignment |
x <<= f() |
x = x << f() |
|
Right shift assignment |
x >>= f() |
x = x >> f() |
|
Unsigned right shift assignment |
x >>>= f() |
x = x >>> f() |
|
x &= f() |
x = x & f() |
|
|
Bitwise XOR assignment |
x ^= f() |
x = x ^ f() |
|
Bitwise OR assignment |
x |= f() |
x = x | f() |
|
Logical AND assignment |
x &&= f() |
x && (x = f()) |
|
Logical OR assignment |
x ||= f() |
x || (x = f()) |
(5) Ternary Operator : JavaScript provides a special operator
called ternary operator :? that assigns a value to a variable based on some
condition. This is the short form of the if else condition.
Syntax:
<condition> ? <value1> :
<value2>;
Example: Ternary operator
let a = 100, b = 50;
let d = a > b? b : a; // value of d
would be 50
HTML PROGRAME
CSS PROGRAME
JAVASCRIPT PROGRAM
HOW TO WRITE THE JAVASCRIPT
PROGRAM , HOW MANY WAYS TO WRITE THE JAVASCRIPT PROGRAM
ANS : THERE ARE THREE WARS TO WRITE THE
JAVASCRIPT PROGRAM
1: console.log() : Through console.log()
we can debag the console program
2: alert()
3: document.write()
1 Q. WAP IN JAVASCRIPT TO
DISPLAY YOURS NAME (using console.log())
MAKE A .html FILE
<!DOCTYPE html>
<html>
<head>
<title>1ST JAVASCRIPT
PROGRAM</title>
<script type=”text/javascript”>
Console.log”(MY NAME IS AJAY KUMAR
PATHAK”);
</script>
</head>
<body>
</body>
</html>
Q. 2. WAP IN JAVASCRIPT TO DISPLAY YOURS NAME (using internal
JavaScript )
MAKE A .html FILE
<!DOCTYPE html>
<html>
<head>
<title>1ST JAVASCRIPT
PROGRAM</title>
<script>document.write(“MY NAME IS
AJAY KUMAR PATHAK, I CAN ALSO WRITE IN HEAD TAG”);
</script>
</head>
<body>
<script>document.write(“MY NAME IS
AJAY KUMAR PATHAK, I CAN ALSO WRITE IN BODY TAG”);
</body>
</html>
JAVASCRIPT ADVANTAGES:-
(1) Simple − JavaScript is simple to comprehend and pick up. Both users and developers will find the structure to be straightforward. Additionally, it is very doable to implement, saving web developers a tonne of money when creating dynamic content.
(2) Speed − JavaScript is a "interpreted" language, it cuts down on the
time needed for compilation in other programming languages like Java. Another
client-side script is JavaScript, which accelerates programme execution by
eliminating the wait time for server connections.
No matter where JavaScript is hosted, it
is always run in a client environment to reduce bandwidth usage and speed up
execution.
(3) Interoperability − Because JavaScript seamlessly integrates with other
programming languages, many developers favour using it to create a variety of
applications. Any webpage or the script of another programming language can
contain it.
(4) Server Load − Data validation can be done within the browser itself rather than being
forwarded to the server because JavaScript is client-side. The entire website
does not need to be reloaded in the event of any discrepancy. Only the chosen
area of the page is updated by the browser.
JAVASCRIPT DISADVANTAGES
(1) Cannot Debug − Although some HTML editors allow for debugging, they are not as effective as editors for C or C++. Additionally, the developer has a difficult time figuring out the issue because the browser doesn't display any errors.
(2) Unexpected stop of rendering − The website's entire JavaScript code can stop rendering due to a single error in the code. It appears to the user as though JavaScript is absent. The browsers, however, are very forgiving of these mistakes.
(3) Client-side Security − The user can see the JavaScript code; it could be misused
by others. These actions might involve using the source code anonymously.
Additionally, it is very simple to insert code into the website that impair the
security of data transmitted via the website.
(4) Inheritance − JavaScript does not support multiple inheritance; only one inheritance
is supported. This property of object-oriented languages might be necessary for
some programmes.
(5) Browser Support − Depending on the browser, JavaScript is interpreted
differently. Therefore, before publication, the code needs to run on various
platforms. We also need to check the older browsers because some new functions
are not supported by them.
FROM HERE I AM USING
EXTERNAL JAVA SCRIPT FOR PROGRAME
STEP
Q1 WAP IN HTML TO
PRINT YOUR NAME USING EXTERNAL JAVASCRIPT
IN HTML
1ST WRITE THIS CODE IN
HTML FILE AND SAVE AS FIL_NAME.HTML
<html>
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading AND
1ST EXTERNAL JAVA SCRIPT FILE</h1>
<p>My first
paragraph.</p>
<script>
type="teal/javascript" src "C:\Users\ajay\Desktop\HTML PROGRAM
FOR EXAMPLE\PLUS_PLUS\1STEXTE_JAVA.js"
</script>
</body>
</html>
NOW MAKE 2ND
JAVASCRIPT FILE
const num1 = 5;
const num2 = 3;
// add two numbers
const sum = num1 + num2;
// display the sum
console.log('The sum of ' +
num1 + ' and ' + num2 + ' is: ' + sum);
JAVA SCRIPT OBJECT
HIERARCHY
WHAT IS JAVA SCRIPT
OBJECT HIERARCHY (WINDOW OBJECTS & ARRAY)
In JavaScript, the object
hierarchy is a way to organize and represent the various objects and elements
in the language.
The two objects you mentioned,
"Window" and "Array," are important parts of this
hierarchy.
(1). WINDOW OBJECT:- The Window object is the top-level object in the
JavaScript object hierarchy when running in a web browser environment. It
represents the browser window or tab that displays a web page. This object
provides access to various properties and methods for interacting with the
browser window and the document loaded within it.
SOME KEY PROPERTIES
AND METHODS OF THE WINDOW OBJECT INCLUDE:
1. window.document: Provides access to the Document Object Model (DOM) of
the web page, allowing you to manipulate and interact with the HTML content.
2. window.location: Contains information about the current URL and allows
you to navigate to other URLs.
3. window.alert(), window.confirm(), and
window.prompt(): Methods for displaying
pop-up dialogs to interact with the user.
4. window.setTimeout() and
window.setInterval(): Functions for
scheduling code to run after a specified delay or at regular intervals.
5. window.localStorage and
window.sessionStorage: Storage objects
for storing data on the client side.
The Window object is a global
object, meaning you can access its properties and methods directly without
prefixing them with window..
(2). ARRAY OBJECT:- The Array object is a built-in JavaScript object that
represents a collection of values organized in an ordered list. Arrays are used
to store and manipulate multiple values in a single variable. You can create
arrays with a list of values enclosed in square brackets, like [1, 2, 3].
SOME COMMON
PROPERTIES AND METHODS OF THE ARRAY OBJECT INCLUDE:
1. length: Property that represents the number of elements in the
array.
2. push(): Method to add one or more elements to the end of an
array.
3. pop(): Method to remove and return the last element of an
array.
4. shift(): Method to remove and return the first element of an
array.
5. unshift(): Method to add one or more elements to the beginning
of an array.
6. concat(): Method to combine two or more arrays into a new
array.
7. splice(): Method for adding or removing elements at a specific
position within an array.
8. forEach(): Method for iterating over the elements of an array
and applying a function to each element.
9. map(), filter(), reduce(): Methods for transforming,
filtering, and aggregating array elements.
Arrays are a fundamental data
structure in JavaScript and are used extensively for various tasks, such as
storing collections of data, iterating over data, and performing operations on
sets of values.
These two objects, Window and
Array, are just a small part of the broader JavaScript object hierarchy.
JavaScript is a versatile and object-oriented language, and it features a wide
range of built-in objects and allows developers to create custom objects, which
can be organized hierarchically based on their relationships and purposes
within a program or application.
VARIOUS EVENTS IN
JAVASCRIPT;-
In JavaScript, events are
actions or occurrences that happen in the browser, such as a user clicking a
button, typing in an input field, or a webpage finishing loading. JavaScript
allows you to respond to these events by executing code when they occur.
Developers can use these events
to execute JavaScript coded responses, which cause buttons to close windows,
messages to be displayed to users, data to be validated, and virtually any
other type of response imaginable.
Events are a part of the
Document Object Model (DOM) Level 3 and every HTML element contains a set of
events which can trigger JavaScript Code.
Events are a fundamental part
of building interactive web applications.
Let's explore various events in
JavaScript in detail:
MOUSE EVENTS:
click: Occurs when a mouse
button is clicked.
dblclick: Occurs when a mouse
button is double-clicked.
mousedown: Occurs when a mouse
button is pressed down.
mouseup: Occurs when a mouse
button is released.
mousemove: Occurs when the
mouse pointer is moved.
mouseover: Occurs when the
mouse pointer enters an element.
mouseout: Occurs when the mouse
pointer leaves an element.
EXAMPLE USAGE:
javascript
Copy code
document.getElementById('myButton').addEventListener('click',
function() {
// Code to execute when the button is clicked
});
KEY BOARD EVENTS:-
keydown: Occurs when a key on
the keyboard is pressed down.
keyup: Occurs when a key on the
keyboard is released.
keypress: Occurs when a key
that produces a character value is pressed down and released.
Example usage:
javascript
Copy code
document.addEventListener('keydown',
function(event) {
if (event.key === 'Enter') {
// Code to execute when the Enter key is
pressed
}
});
Form Events:
submit: Occurs when a form is
submitted.
input: Occurs when the value of
an input element changes.
focus: Occurs when an element
receives focus.
blur: Occurs when an element
loses focus.
Example usage:
javascript
Copy code
document.getElementById('myForm').addEventListener('submit',
function(event) {
event.preventDefault(); // Prevents the form
from submitting
// Code to handle form submission
});
Window Events:
load: Occurs when a webpage
finishes loading.
resize: Occurs when the browser
window is resized.
scroll: Occurs when the user
scrolls the page.
unload: Occurs when a webpage
is about to be unloaded (e.g., when navigating away from the page).
Example usage:
javascript
Copy code
window.addEventListener('load',
function() {
// Code to execute when the page finishes
loading
});
Custom Events:
You can create and dispatch
custom events in JavaScript using the CustomEvent constructor. This allows you
to define and trigger your own custom events within your application.
Example usage:
javascript
Copy code
const customEvent = new
CustomEvent('myCustomEvent', { detail: 'Some data' });
document.dispatchEvent(customEvent);
document.addEventListener('myCustomEvent',
function(event) {
const data = event.detail;
// Code to handle the custom event
});
1. EXAMPLE OF ONCLICK EVENT FOR PRACTICAL
<html>
<head>
<script type =
"text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following
button and see result</p>
<form>
<input type =
"button" onclick = "sayHello()" value = "Say
Hello" />
</form>
</body>
</html>
OUTPUT
(2) EXAMPLE ONSUBMIT EVENT PRACTICAL
onsubmit is an event that
occurs when you try to submit a form. You can put your form validation against
this event type.
<html>
<head>
<script type =
"text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method =
"POST" action = "t.cgi" onsubmit = "return
validate()">
.......
<input type =
"submit" value = "Submit" />
</form>
</body>
</html>
OUTPUT
JAVASCRIPT METHODS:-
A function is a code of some
instructions which performs a task OR A method is a function that belongs to
some object or a set of some instructions that performs a certain task.
Below, I'll provide explanations and examples
for some commonly used JavaScript methods from various categories:
(1). String Methods:
(a). charAt(index):
Returns the character at the specified index in a string.
Example 1
const str = "Hello, World!";
const char = str.charAt(7); // Returns
'W'
concat(str1, str2, ...): Combines two or
more strings and returns a new string.
Example 2
const str1 = "Hello, ";
const str2 = "World!";
const result = str1.concat(str2); //
Returns 'Hello, World!'
(b). indexOf(searchValue,
startIndex): Returns the
index of the first occurrence of a specified substring in a string, or -1 if
not found.
Example 1
const str = "Hello, World!";
const index =
str.indexOf("World"); // Returns 7
( c) . toUpperCase(): Converts a string to uppercase.
Example 1
const str = "Hello, World!";
const upper = str.toUpperCase(); //
Returns 'HELLO, WORLD!'
(d) concat( ) :This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.
Example 1
const arr1=[“a”,”b”,”c”];
const arr2=[“d”,”e”,”f”];
console.log(arr1.concat(aar2));
console.log(arr1);
console.log(arr2);
(2). Array Methods:
(a). push(item): Adds one or more items to the end of an
array and returns the new length.
Example
const arr = [1, 2, 3];
const length = arr.push(4); // Returns 4
and arr becomes [1, 2, 3, 4]
(b). pop(): Removes and returns the last
item from an array.
Example
const arr = [1, 2, 3, 4];
const removed = arr.pop(); // Returns 4
and arr becomes [1, 2, 3]
( c). join(separator): Converts an array into a string by
joining its elements with the specified separator.
Example
const arr = ["apple",
"banana", "cherry"];
const joined = arr.join(", ");
// Returns 'apple, banana, cherry'
(d). map(callback): Creates a new array by applying a
function to each element of the original array.
Example
const arr = [1, 2, 3];
const doubled = arr.map((item) =>
item * 2); // Returns [2, 4, 6]
(3). Object Methods:
(a). Object.keys(obj): Returns an array of an object's own
property names.
Example
const person = { name: "John",
age: 30 };
const keys = Object.keys(person); //
Returns ['name', 'age']
(b). Object.values(obj): Returns an array of an object's own
property values.
Example
const person = { name: "John",
age: 30 };
const values = Object.values(person); //
Returns ['John', 30]
( c).
Object.hasOwnProperty(prop): Checks if an object has a specific property and returns a boolean.
Example
const person = { name: "John",
age: 30 };
const hasName =
person.hasOwnProperty("name"); // Returns true
(d). filter( ) :This method creates a new array with
only elements that passes the condition inside the provided function.
Example
Return an array of all values in ages[]
that are 18 or over:
const ages = [32, 33, 16, 40];
const result = ages.filter(checkAdult);
function checkAdult(age) {
return age >= 18;
}
(e). sort( ): This method is used to arrange/sort
array’s elements either in ascending or descending order.
Example
const fruits = ["Banana",
"Orange", "Apple", "Mango"];
fruits.sort();
PROGRAM FOR PRACTICAL
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrays</h2>
<p>The Array.sort() method sorts
the elements of an array.</p>
<p id="demo"></p>
<script>
const fruits = ["Banana",
"Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML
= fruits.sort();
</script>
</body>
</html>
OUTPUT
OBJECTS OF JAVASCRIPT
:-
In JavaScript, objects are one
of the fundamental data types and play a central role in the language. They are
used to represent and store data in the form of key-value pairs, where each key
is a unique identifier (usually a string), and the associated value can be of
any data type, including other objects. Objects in JavaScript are versatile and
can be used to model real-world entities and their properties.
Here's a detailed explanation
of objects in JavaScript with a full example:
Creating an Object
You can create an object in
JavaScript using two main methods: object literal notation and the Object
constructor.
Object Literal Notation:
EXAMPLE
const person = {
firstName: "John",
lastName: "Doe",
age: 30,
email: "john@example.com",
};
In this example, we've created
an object named person using curly braces {}. The object contains four
key-value pairs, where the keys are strings (e.g., "firstName") and
the values can be of various data types.
Object Constructor:
EXAMPLE
const person = new Object();
person.firstName =
"John";
person.lastName =
"Doe";
person.age = 30;
person.email =
"john@example.com";
Here, we create an empty object
with the Object constructor and then add properties to it using dot notation.
Accessing Object Properties
You can access the properties
of an object using dot notation or square brackets.
EXAMPLE
console.log(person.firstName);
// "John"
console.log(person["lastName"]);
// "Doe"
Modifying Object Properties
You can modify the values of
object properties by assigning new values to them.
EXAMPLE
person.age = 31;
console.log(person.age); // 31
Adding New Properties
You can add new properties to
an existing object by simply assigning values to new keys.
EXAMPLE
person.address = "123 Main
St";
console.log(person.address); //
"123 Main St"
Deleting Properties
You can delete properties from
an object using the delete keyword.
EXAMPLE
delete person.email;
console.log(person.email); //
undefined
Object Methods
In addition to properties,
objects can also have methods, which are functions stored as object properties.
EXAMPLE
const calculator = {
add: function (a, b) {
return a + b;
},
subtract: function (a, b) {
return a - b;
},
};
console.log(calculator.add(5,
3)); // 8
console.log(calculator.subtract(10,
4)); // 6
Iterating Through Object
Properties
You can loop through the
properties of an object using a for...in loop.
EXAMPLE
for (let key in person) {
console.log(key + ": " +
person[key]);
}
This loop will output each
property and its value in the person object.
Object Literal
Shorthand
In modern JavaScript, you can
use shorthand when creating objects if the property names match the variable
names.
EXAMPLE
const firstName =
"Jane";
const lastName =
"Smith";
const user = { firstName,
lastName };
console.log(user); // {
firstName: "Jane", lastName: "Smith" }
Object Destructuring
You can destructure object
properties into variables for easy access.
EXAMPLE
const { firstName, lastName } =
person;
console.log(firstName); //
"John"
console.log(lastName); //
"Doe"
DECISION MAKING AND
LOOP FORMING STATEMENTS / CONTROL STRUCTURES / CONTROL STATEMENTS :-
In JavaScript, decision making
refers to the process of using conditional statements to make choices or
decisions in your code. Conditional statements allow you to execute different
blocks of code based on whether a specified condition evaluates to true or
false. This is a fundamental concept in programming and is essential for
creating dynamic and responsive applications.
There are several
ways to implement decision making in JavaScript:
JavaScript’s
conditional statements are:
1) if
2) if-else
3) if…else…if
4) switch
1) if statement:- if statement is the most simple decision making
statement.It is used to decide whether a certain statement or block of
statements will be executed or not.If a certain condition is true then a block
of statement is executed otherwise not.
Syntax
if ( condition )
{
// block of code to be executed
}
You can omit the braces if
there is only single statement in block.
2) if…else
statement:- The if-else statement has two
parts if block and else block.If the condition is true then if block (true
block) will get executed and if the condition is false then else block (false
block) will get executed.
Syntax
if ( condition )
{
// block of code to be executed when
condition is true
}
else
{
// block of code to be executed when
condition is false
}
3) if…else…if
statement:- The if…else…if statement is an advanced
form of if…else that allows JavaScript to make a correct decision out of
several conditions.
All the if conditions will be
checked one by one. If any condition is true out of given then that block will
get executed and other blocks are skipped.
Syntax
if ( condition 1 )
{
// block of code to be executed when
condition 1 is true
}
else if ( condition 2 )
{
// block of code to be executed when
condition 2 is true
}
else if ( condition 3 )
{
// block of code to be executed when
condition 2 is true
}
else
{
// block of code to be executed if no
condition matches
}
4) switch statement:- The objective of a switch statement is to give an
expression to evaluate and several different statements to execute based on the
value of the expression.The interpreter checks each case against the value of
the expression until a match is found. If nothing matches, a default condition
will be used.
Syntax
switch (expression)
{
case c1: statement(s)
break;
case c2: statement(s)
break;
...
case cn: statement(s)
break;
default: statement(s)
}
LOOPING STATEMENTS:-
Looping in programming languages
facilitates the execution of a set of instructions/functions repeatedly while
some condition evaluates to true.
For example, suppose we want to print
“Hello World” 10 times this is possible with the help of loops.
There are mainly two types of
loops:
1) Entry Controlled loops: In this type of loops the test
condition is tested before entering the loop body. For Loop and While Loop are
entry controlled loops.
2) Exit Controlled Loops: In this type of loops the test
condition is tested or evaluated at the end of loop body. Therefore, the loop
body will execute atleast once, irrespective of whether the test condition is
true or false. do-while loop is exit controlled loop.
Following are the types of
loops in JavaScript:
1) while loop
2) do-while loop
3) for loop
4) for…in loop
1) while loop :- A while loop is a entry-controlled loop
that allows code to be executed repeatedly if the condition is true.
When the condition becomes false, the
loop terminates which marks the end of its life cycle.
The while loop executes ZERO or MORE
times.
Syntax
while (condition)
{
// Statements to be executed
}
2) do-while loop :- A do-while loop is a exit-controlled
loop that allows code to be executed first and after that checks for condition
and depending on that it executed repeatedly.
When the condition becomes false, the
loop terminates which marks the end of its life cycle.
The do-while loop executes ONE or MORE
times.
Syntax
do
{
// Statements to be executed
}
while (condition);
3) for loop :- A for loop is a entry-controlled loop
that allows code to be executed repeatedly.
It provides a concise way of writing the
loop structure.
Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.
The for loop executes ZERO or MORE times
Syntax
for (initialization; condition;
increment/decrement)
{
// Statements to be executed
}
4) for…in loop :-
(For-in loop in JavaScript is used to iterate over the properties of an
object. The for-in loop iterates only over those keys of an object which have
their enumerable property set to “true”. The key values in an object have four
attributes (value, writable, enumerable, and configurable).
JavaScript also includes another version
of for loop also known as the for..in loops.
The for..in loop provides a simpler way
to iterate through the properties of an object.
This loop is seen to be very useful
while working with objects.
In each iteration, one of the properties
of Object is assigned to the variable named variableName and this loop
continues until all of the properties of the Object are processed.
Syntax
for (variableName in Object)
{
// Statements to be executed
}
EXAMPLE WITH PROGRAM OF for…in loop
(MAKE WITH HTML)
//declaring a object employee
const courses = {
firstCourse: 'AJAY',
secondCourse: 'KUMAR',
thirdCourse: 'PATHAK'
};
let value = '';
//using for in loop
for (let item in courses) {
value += courses[item] + " "; OR value = value+courses[item] +
" ";
}
console.log(value);
OUTPUT
AJAY KUMAR PATHAK
PROGRAM, EXAMPLE OF LOOPING STATEMENTS
Develop JavaScript to use decision
making & looping statements.
1. DECISION MAKING: FIND
WHETHER IS NUMBER IS EVEN OR ODD.
SAVE AS FILENAME.HTML
<html>
<head>
<script
type="text/javascript"> var x=24;
if(x%2==0)
{
document.write("<h3>The Given
Number is Even Number</h3>");
}
else
{
document.write("<h3>The Given
Number is Odd Number</h3>");
}
</script>
</head>
<body>
</body>
</html>
EXAMPLE FOR PRACTICAL OF LOOPS
AND DECISION MAKING CONDITION
Q2 :- TO CHECK THE NUMBER IS
EVEN OR ODD
<html>
<head>
<title>
Practical_1
</title>
</head>
<body>
<h1>Practical No.2</h1>
<p><b>Aim</b> :
Develop JavaScript to use decision making and looping
statement.</p><hr>
<script
type="text/javascript">
document.write("<b>Check
the Number is even or odd ?</b><br>");
let a =0;
a = prompt("Enter the
new Number:");
document.write("<br>")
if (a%2==0)
document.write(a," is
a even number");
else
document.write(a," is
odd number<br>");
document.write("<hr>");
document.write("<b>Printing the Table of :</b>
",a,"<br>" );
for(let i=1;i<=10;i++) {
document.write("<br>",i*a);
}
</script>
</body>
</html>
PRACTICAL NO 3: USING SWITCH
CASE (NO INPUT ONLY DISPLAY)
<html>
<body>
<script
type="text/javascript">
var d = new Date();
theDay = d.getDay();
switch (theDay) {
case 5:
document.write("<b>Finally Friday</b>");
break;
case 6:
document.write("<b>Super Saturday</b>");
break;
case 0:
document.write("<b>Sleepy Sunday</b>");
break;
default:
document.write("<b>I'm really looking forward to this
weekend!</b>");
}
</script>
<p>
This JS code will generate a different
greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.
</p>
</body>
</html>
OUTPUT
LOOPING STATEMENTS:-
Looping in programming
languages facilitates the execution of a set of instructions/functions repeatedly
while some condition evaluates to true.
For example, suppose we want to
print “Hello World” 10 times this is possible with the help of loops.
There are mainly two types of
loops:
1) Entry Controlled
loops:- In this type of loops the test
condition is tested before entering the loop body. For Loop and While Loop are
entry controlled loops.
2) Exit Controlled
Loops:- In this type of loops the test
condition is tested or evaluated at the end of loop body. Therefore, the loop
body will execute atleast once, irrespective of whether the test condition is
true or false. do-while loop is exit controlled loop.
Following are the
types of loops in JavaScript:
1) while loop
2) do-while loop
3) for loop
4) for…in loop
1) while loop :- A while loop is a entry-controlled loop that allows
code to be executed repeatedly if the condition is true.
When the condition becomes
false, the loop terminates which marks the end of its life cycle.
The while loop executes ZERO or
MORE times.
Syntax
while (condition)
{
// Statements to be executed
}
2) do-while loop :- A do-while loop is a exit-controlled loop that allows
code to be executed first and after that checks for condition and depending on
that it executed repeatedly.
When the condition becomes
false, the loop terminates which marks the end of its life cycle.
The do-while loop executes ONE
or MORE times.
Syntax
do
{
// Statements to be executed
} while (condition);
3) for loop :- A for loop is a entry-controlled loop that allows
code to be executed repeatedly.
It provides a concise way of
writing the loop structure.
Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one
line thereby providing a shorter, easy to debug structure of looping.
The for loop executes ZERO or
MORE times
Syntax
for (initialization; condition;
increment/decrement)
{
// Statements to be executed
}
4) for…in loop : (For-in loop
in JavaScript is used to iterate over the properties of an object. The for-in
loop iterates only over those keys of an object which have their enumerable
property set to “true”. The key values in an object have four attributes
(value, writable, enumerable, and configurable).
JavaScript also
includes another version of for loop also known as the for..in loops.
The for..in loop provides a
simpler way to iterate through the properties of an object.
This loop is seen to be very
useful while working with objects.
In each iteration, one of the
properties of Object is assigned to the variable named variableName and this
loop continues until all of the properties of the Object are processed.
Syntax
for (variableName in Object)
{
// Statements to be executed
}
EXAMPLE WITH PROGRAM
OF for…in loop
(MAKE WITH HTML)
//declaring a object employee
const courses = {
firstCourse: 'AJAY',
secondCourse: 'KUMAR',
thirdCourse: 'PATHAK'
};
let value = '';
//using for in loop
for (let item in courses) {
value += courses[item] + " "; OR
value = value+courses[item] + " ";
}
console.log(value);
OUTPUT
AJAY KUMAR PATHAK
PROGRAM, EXAMPLE OF LOOPING STATEMENTS
Develop JavaScript to use
decision making & looping statements.
1. DECISION MAKING:
FIND WHETHER IS NUMBER IS EVEN OR ODD.
SAVE AS FILENAME.HTML
<html>
<head>
<script
type="text/javascript"> var x=24;
if(x%2==0)
{
document.write("<h3>The
Given Number is Even Number</h3>");
}
else
{
document.write("<h3>The
Given Number is Odd Number</h3>");
}
</script>
</head>
<body>
</body>
</html>
EXAMPLE FOR PRACTICAL
OF LOOPS AND DECISION MAKING CONDITION
Q2 :- TO CHECK THE
NUMBER IS EVEN OR ODD
<html>
<head>
<title>
Practical_1
</title>
</head>
<body>
<h1>Practical
No.2</h1>
<p><b>Aim</b>
: Develop JavaScript to use decision making and looping
statement.</p><hr>
<script type="text/javascript">
document.write("<b>Check
the Number is even or odd ?</b><br>");
let a =0;
a = prompt("Enter the
new Number:");
document.write("<br>")
if (a%2==0)
document.write(a," is a even
number");
else
document.write(a," is
odd number<br>");
document.write("<hr>");
document.write("<b>Printing the Table of :</b>
",a,"<br>" );
for(let i=1;i<=10;i++) {
document.write("<br>",i*a);
}
</script>
</body>
</html>
PRACTICAL NO 3: USING
SWITCH CASE (NO INPUT ONLY DISPLAY)
<html>
<body>
<script
type="text/javascript">
var d = new Date();
theDay = d.getDay();
switch (theDay) {
case 5:
document.write("<b>Finally
Friday</b>");
break;
case 6:
document.write("<b>Super
Saturday</b>");
break;
case 0:
document.write("<b>Sleepy
Sunday</b>");
break;
default:
document.write("<b>I'm really
looking forward to this weekend!</b>");
}
</script>
<p>
This JS code will generate a
different greeting based on what day it is. Note that Sunday=0, Monday=1,
Tuesday=2, etc.
</p>
</body>
</html>
OUTPUT
Q4. Looping Statements:
JavaScript for find whether is number is EVEN between 1 to 20.
SAVE AS FILENAME.HTML
<html>
<head>
<script
type="text/javascript">
document.write("<b>Using
do...while loops </b><br />"); var i = 2;
document.write("Even numbers less
than 20<br />"); do
{
document.write(i + "<br
/>"); i = i + 2;
}while(i<20)
</script>
</head>
<body>
</body>
</html>
Q5; PROGRAM OF for…in loop IN
JAVASCRIPT WITH HTML AND TAKE VALUE BY KEYBOARD SIMPLE EXAMPLE
SAVE AS FILENAME.HTML
<!DOCTYPE html>
<html>
<head>
<title>For...in Loop
Example</title>
</head>
<body>
<h1>For...in Loop
Example</h1>
<label
for="inputValue">Enter a value:</label>
<input type="text"
id="inputValue">
<button
onclick="processValue()">Process Value</button>
<p
id="output"></p>
<script>
function processValue() {
// Get the input value from the
user
const inputValueElement =
document.getElementById("inputValue");
const inputValue =
inputValueElement.value;
// Display the input value
const outputElement =
document.getElementById("output");
outputElement.textContent = `You
entered: ${inputValue}`;
}
</script>
</body>
</html>
OUTPUT
Q6: USE JAVASCRIPT
PROGRAMMING CODE TO VALIDATE THE PALINDROME NUMBERS OR STRINGS
SAVE AS FILENAME.HTML
<html>
<head><title>
JavaScript Palindrome </title>
</head>
<body>
<!-- Use JavaScript
programming code to validate the Palindrome numbers or strings. -->
<script>
function validatePalin(str) {
// get the total length of the words
const len = string.length;
// Use for loop to divide the words into 2
half
for (let i = 0; i < len / 2; i++) {
// validate the first and last
characters are same
if (string[i] !== string[len - 1 - i])
{
alert( 'It is not a palindrome');
}
}
alert( 'It is a palindrome');
}
// accept the string or number
from the prompt
const string = prompt('Enter a
string or number: ');
const value =
validatePalin(string);
console.log(value);
</script>
</body>
</html>
Q7: - SIMPLE HTML AND
JAVASCRIPT CODE EXAMPLE TO CHECK IF A NUMBER IS A PALINDROME OR NOT: (OK)
SAVE AS FILENAME.HTML
<!Doctype html>
<html lang =
"en">
<head>
<title> Palindrome
Program in JavaScript </title>
<style>
h1 {
text-align: center;
padding: 30px;
background-color: skyblue;
color: white;
}
.palindrome {
margin: auto;
width: 40%;
border: 3px solid gray;
border-radius: 5px;
padding: 30px;
}
#palindrome {
width: 100%;
border: 3px solid gray;
border-radius: 5px;
padding: 6px;
}
</style>
</head>
<body>
<h1> Palindrome Program
in JavaScript </h1>
<div
class="palindrome">
<label> Enter any string
or number : </label><br><br>
<input id=
"palindrome"><br><br>
<button type =
"button" onclick = "palindrome()" > Check
</button>
</div>
</body>
</html>
<script>
function palindrome() {
var a, b, no, temp = 0;
no = Number(document.getElementById
("palindrome").value);
b = no;
while (no > 0)
{
a = no % 10;
no = parseInt( no / 10);
temptemp = temp*10 + a;
}
if (temp == b)
{
alert( "It is a Palindrome
Number");
}
else
{
alert ("it is not a Palindrome
Number");
}
}
</script></body></html>
Q8: HTML AND
JAVASCRIPT CODE FOR A PROGRAM THAT CHECKS IF A GIVEN STRING IS A PALINDROME OR
NOT:
SAVE AS FILENAME.HTML
<!DOCTYPE html>
<html>
<head>
<title>Palindrome
Checker</title>
<script>
function isPalindrome(str) {
// Remove non-alphanumeric
characters and convert to lowercase
str = str.replace(/[^a-zA-Z0-9]/g,
'').toLowerCase();
// Compare the original string with
its reverse
return str ===
str.split('').reverse().join('');
}
function checkPalindrome() {
var input =
document.getElementById('inputString').value;
var result = isPalindrome(input);
var resultElement =
document.getElementById('result');
if (result) {
resultElement.innerText = 'Yes,
it is a palindrome!';
} else {
resultElement.innerText = 'No,
it is not a palindrome.';
}
}
</script>
</head>
<body>
<h1>Palindrome
Checker</h1>
<p>Enter a string to
check if it is a palindrome:</p>
<input type="text"
id="inputString" placeholder="Enter a string">
<button onclick="checkPalindrome()">Check</button>
<p
id="result"></p>
</body>
</html>
Q9:ARMSTRONG PROGRAM
IN JAVASCRIPT WITH HTML (also known as a narcissistic number or pluperfect
digital invariant) EXAMPLE 153
SAVE AS FILENAME.HTML
<!DOCTYPE html>
<html>
<head>
<title>Armstrong Number
Checker</title>
</head>
<body>
<h1>Armstrong Number
Checker</h1>
<p>Enter a number to
check if it's an Armstrong number:</p>
<input
type="number" id="numberInput">
<button
onclick="checkArmstrong()">Check</button>
<p
id="result"></p>
<script>
function checkArmstrong() {
const number =
parseInt(document.getElementById('numberInput').value);
const numString =
number.toString();
const numDigits = numString.length;
let sum = 0;
for (let i = 0; i < numDigits;
i++) {
const digit =
parseInt(numString.charAt(i));
sum += Math.pow(digit,
numDigits);
}
if (sum === number) {
document.getElementById('result').innerHTML = `${number} is an Armstrong
number!`;
} else {
document.getElementById('result').innerHTML = `${number} is not an
Armstrong number.`;
}
}
</script>
</body>
</html>
Q10: PRIME NO PROGRAM
IN JAVASCRIPT WITH HTML FULL CODE
SAVE AS
FILENAME.HTML( EXAMPLE 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
<!DOCTYPE html>
<html>
<head>
<title>Prime Number
Checker</title>
</head>
<body>
<h1>Prime Number
Checker</h1>
<p>Enter a number to
check if it's prime:</p>
<input
type="number" id="numberInput">
<button
onclick="checkPrime()">Check Prime</button>
<p
id="result"></p>
<script>
function isPrime(number) {
if (number <= 1) {
return false;
}
if (number <= 3) {
return true;
}
if (number % 2 === 0 || number % 3
=== 0) {
return false;
}
for (let i = 5; i * i <= number;
i += 6) {
if (number % i === 0 || number % (i +
2) === 0) {
return false;
}
}
return true;
}
function checkPrime() {
const numberInput =
document.getElementById("numberInput").value;
const resultElement =
document.getElementById("result");
if (isPrime(numberInput)) {
resultElement.textContent =
numberInput + " is a prime number.";
} else {
resultElement.textContent =
numberInput + " is not a prime number.";
}
}
</script>
</body>
</html>
THE END
FUNCTIONS IN
JAVASCRIPT :-
Functions are the basic
building block of JavaScript. Functions allow us to encapsulate a block of code
and reuse it multiple times.Functions make JavaScript code more readable,
organized, reusable, and maintainable.
In JavaScript, a function can
be defined using the “function’ keyword, followed by the name of a function and
parentheses. Optionally, a list of input parameters can be included within the
parentheses. The code block that needs to be executed when the function is
called is written within curly braces.
A function in JavaScript is a
block of code that contains a group of instructions to perform a particular
task.
For example, write() is an
in-built JavaScript function that is used to print a statement.
A function does not execute
until it is called. That is, a function will execute when “someone” invokes
it.When a function gets called, the code inside the function executes. We can
call a function from other parts of the program when needed.
In JavaScript programming, we
can define our own functions,
called user-defined functions
as well as use built-in functions already defined in JavaScript. For example,
we have used the in-built
functions, such as: built-in functions
document.write() // To write in
document file
window.alert() // To display a
message box on screen like ok, cancel, submit etc
parseInt() // To convert string
to integer only in VB Studio like C# , Windows programming etc.
Syntax
function
<function-name>(arg1, arg2, arg3,...)
{
//write function code here
};
TYPES OF FUNCTIONS IN
JAVASCRIPT
There are two types of
functions in JavaScript like any other programming language such as C, C++, and
Java.
(1). Predefined
functions:-
1. alert(): This function displays an alert dialog box on the
browser.
2. confirm(): This function displays a confirmation dialog box and
asks the user to choose one from two options.
3. prompt(): The prompt() function displays a prompt dialog box on
the browser and prompts the user to enter input.
4. write(): The write() function used to write something on the
document.
5. Date(): This function used to get the current date and time.
6. select(): The select() function used to select the pointed
object.
7.
parseInt(numString): This function
converts a string into an integer.
8.
parseFloat(numString, radix): This
function converts a string into floating point number.
9. sqrt(number): This function used to get the square root of any
number.
10. pow(number): It used to get the power of an integer.
(2). User-defined
functions :-
JavaScript also allows to
create your own user-defined function. With the help of user-defined function,
functionName([arguments]);
For example:
sayHello();
1, SIMPLE EXAMPLE OF
FUNCTION WITH PROGRAM
SAVE AS FILENAME.HTML
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Function Parameters</h1>
<script>
function abc(firstName, lastName) {
alert("Hello " +
firstName + " " + lastName);
}
abc("AJAY", "PATHAK"); /*
FUNCTION CALLING*/
abc(1000, 2000);/* FUNCTION CALLING */
</script>
</body>
</html>
2, SIMPLE EXAMPLE OF
FUNCTION WITH PROGRAM
<html>
<head>
<title>Functions in
JavaScript</title>
<script>
var msg = "Welcome to Mrs KMPM
students";
// Function declaration.
function display() {
document.write(msg); // It will print
statement in web browser.
}
</script>
</head>
<body>
<script>
display(); // Calling function.
</script>
</body>
</html>
3.. EXAMPLE: RETURN
VALUE FROM A FUNCTION
<!DOCTYPE html>
<html>
<body>
<h1>Demo: Return Value from a Function</h1>
<p id="p1"></p>
<script>
function Sum(num1, num2) {
return num1 + num2;
};
var result = Sum(10,20);
document.getElementById("p1").innerHTML
= result;
</script>
</body>
</html>
4.. EXAMPLE CALCULATE
ADDITION, SUBTRACTION, MULTIPLICATION
DIVISION FOR
PRACTICAL (OK)
(Calling Functions from other
Functions in JavaScript)
<html>
<head>
<title>Calling functions
from other functions.</title>
<script>
// Variable declaration.
let x = 20;
let y = 30;
// Function 1.
function addition() {
let sum = x + y;
document.write("Sum = " +sum,
"<br>");
}
// Function 2.
function subtraction() {
let sub = x - y;
document.write("Sub = " +sub,
"<br>");
}
// Function 3.
function multiplication() {
let multiply = x * y;
document.write("Multiply = " +
multiply, "<br>");
}
// Function 4.
function division() {
let div = x / y;
document.write("Div = " +div);
}
// Calling functions inside
from function.
function main() {
addition();
subtraction();
multiplication();
division();
}
main(); // calling function.
</script>
</head>
<body>
</body>
</html>
OUTPUT:
Sum = 50
Sub = -10
Multiply = 600
Div
= 0.666666
(NOT IN SYLLABUS)
ARROW FUNCTIONS IN JAVASCRIPT (Arrow functions were introduced in ES6 (means
advance version )
Arrow functions are anonymous
functions i.e. functions without a name and are not bound by an identifier.
Arrow functions do not return any value and can be declared without the
function keyword. They are also called Lambda Functions. Syntax: const abc = () => { console.log( "Hello
Ajay!" ); }
PROGRAM OF ARROW
FUNCTION
SAVE AS FILENAME.HTML
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Functions</h1>
<h2>The Arrow Function</h2>
<p>This example shows the
syntax of an Arrow Function and how to use it </p>
<p
id="demo"></p>
<script>
let hello = "";
hello = () => {
return "Hello World!";
}
document.getElement ById
("demo").innerHTML = hello();
</script>
</body></html>
DYNAMIC HTML WITH
JAVA SCRIPT:-
((( Definition of Dynamic HTML (DHTML)
with JavaScript:- Dynamic HTML (DHTML) is
a web development technique that uses a combination of HTML, CSS, and
JavaScript along with the Document Object Model (DOM) to create interactive and
dynamic web pages, where the content, structure, and style of a webpage can be
modified in real-time without reloading the page.
Dynamic HTML refers to the
ability of a web page to change its content, layout, and appearance dynamically
in response to user actions or events (such as clicking a button, entering
data, or moving the mouse), by using JavaScript to manipulate HTML elements
through the DOM.
Key Points Included in the
Definition:-
·
It is not a
separate language, but a combination of technologies.
·
It allows
real-time updates on a webpage.
·
It uses
JavaScript as the main scripting language.
·
It works through
the DOM to access and modify elements.
·
It eliminates the
need for page reloading for changes.
)))
WHAT IS DYNAMIC HTML:-
DHTML, or Dynamic HTML, is a combination
of HTML, cascading style sheets (CSS), and JavaScript used to create dynamic
and interactive web pages. With DHTML, you can make web page elements change
without needing a full page reload, enhancing the user's experience.
DHTML is a mixture of
technologies such as HTML, CSS, and javascript where, HTML provides structure
to a webpage, CSS gives visual effects, and Javascript is used for
functionalities. This mixture helps to change the appearance and content of web
pages dynamically.DHTML helps in creating a responsive and interactive website
FOR EXAMPLE, the drop-downs,
animations, events, links, include drag-drop functionality, events, animations,
input forms, menus, cursors, images, etc. , are examples of DHTML. The DHTML
uses the DOM (document object model) for making changes to a website's content.
The dynamic property in DHTML comes from technologies such as CSS, HTML, DOM
and Javascript, and other static languages, which helps make it dynamic.
Why Use DHTML?:-
i.
Dynamic Content:-
DHTML allows for the creation of dynamic and interactive web pages.
ii. Enhanced User Experience:- With DHTML, web pages can
respond to user actions in real-time, providing a more engaging experience.
iii. Reduced Server Load:- DHTML enables client-side
scripting, reducing the need for server requests and thereby decreasing server
load.
iv. Faster Page Load Times:- By dynamically updating
content without full page reloads, DHTML can significantly improve page load
times.
v. Richer User Interfaces:- DHTML enables the creation of
rich user interfaces with features like drag-and-drop, animations, and
interactive forms.
vi. Cross-Browser Compatibility:- DHTML is supported by
most modern web browsers, ensuring compatibility across different platforms and
devices.
Difference between
HTML and DHTML:-
|
Parameters |
HTML |
DHTML |
|
Definition |
Stands for HyperText Markup
Language. |
Stands for Dynamic HTML. |
|
Nature |
Static and primarily used for
structuring web content. |
Dynamic and allows for
interactive and animated web pages. |
|
Interactivity |
Limited interactivity without
the need for scripting. |
Highly interactive with
extensive use of client-side scripting. |
|
Page Refresh |
Requires full page reloads to
update content. |
Updates content dynamically
without full page reloads. |
|
Scripting |
Minimal or no client-side
scripting. |
Relies heavily on client-side
scripting languages like JavaScript. |
|
Browser Support |
Supported by all web
browsers. |
Requires modern web browsers
with support for JavaScript and CSS. |
|
Complexity |
Simple and straightforward
markup language. |
More complex due to dynamic
behaviors and scripting. |
|
Use Cases |
Suitable for static web pages
and basic content presentation. |
Ideal for creating dynamic
web applications and interactive websites. |
DHTML Components:-
(1) HTML 4.0:-
·
It stands for
hypertext markup language.
·
It is used to
give structure to our webpage.
·
HTML 4. O is an
HTML version with several new features like scripting languages, style sheets,
multimedia options, and better printing facilities.
(2) CSS:-
·
CSS stands for
cascading style sheets.
·
It handles an
image's alignment size and border in a blog or post.
·
It’s like a group
of instructions that gives structure and style to our webpage.
·
CSS is used to
provide style to our webpage by designing HTML tags.
·
It adds fonts,
colors, and layouts to our webpage.
·
Using CSS, we can
also create animations by using “@keyframes.” It is used for controlling
intermediate steps in a CSS animation sequence.
(3) Javascript:-
·
As we have provided
structure and design to our website, the next step involves providing
functionality to our webpage.
·
Using Javascript,
we can add interactivity and dynamic functionality to our web pages.
·
It helps us in
executing complex actions.
·
Using Javascript,
we can enable the interaction of websites with visitors.
·
We can also load
the content in a document without reloading the webpage.
·
Using plugins is
made more accessible by javascript. They extend the functionality of a webpage.
(4) DOM(Document Object Model):-
·
It is a
programming interface for accessing and manipulating HTML elements.
·
Using DOM, we can
interact with the content and structure of a webpage.
·
When a webpage is
loaded, a document object model is created by the browser.
·
The HTML DOM
model is like a tree of objects.
·
Using the object
model, javascript gets the power for creating dynamic HTML. Therefore
javascript can change all the HTML elements and attributes, CSS styles, remove
existing HTML elements and attributes, add new HTML existing elements and
attributes, and can react to all existing HTML events in the page using DOM
DHTML Advantages:-
i.
Interactive UI:-
DHTML helps provide an interactive user interface to our web pages.
ii. Compact File Size:- DHTML is compact compared to other
multimedia software like Shockwave and Flash. This saves bandwidth and time.
iii. Dynamic content:- It has a major plus point that we
can dynamically change the appearance and content of web pages according to the
user's needs.
iv. Cross-Browser Compatibility:- DHTML is compatible with
all modern web browsers, i.e., they all support DHTML.
v. Efficient:- DHTML is efficient, and the files are
maintainable, which means that web designers have more flexibility due to
DHTML.
vi. Less Server Load:- As we can create dynamic web pages
using DHTML, it helps in reducing server load and improves overall performance.
DHTML Disadvantages:-
i.
As we have
discussed, DHTML uses various technologies. Therefore, it is advised to have a
good command of them.
ii. We need to check browser compatibility while using
DHTML as it is not sure that it will perform on each and every platform.
iii. Maintaining
DHTML code can be a tedious task.
DHTML Events:- An event refers
to an action or occurrence in a browser. For instance, when we click on a
button or when we scroll. Events change the appearance of elements on the page
or trigger scripts. For example, when we click on a button on a webpage, there
is a change in the color of a specific HTML element, or there are events
related to the mouse’s action, such as when we scroll on a webpage and an event
occurs on the webpage. We can also create some scroll animations using this
property.
Types of events:-
(I) Window Events:- These events get triggered when the state of
the window changes. Some examples of window events are mentioned below.
(a) scroll:- It gets triggered whenever we scroll the window.
(b) resize:- resize events are triggered when the user changes
the size of the window.
(c ) load:- This event is
triggered when the window has finished loading all resources.
(2) Document Events:- Document events are related to the webpage’s content.
They are triggered when the
state of the document changes.
(a) Keyboard Events-Theses are the events related to keyboard
activities, such as when we press a key on the keyboard and a change occurs on
our webpage. For instance, when we press enter, we can submit a form on the
website.
(b) click-These are the events triggered when the user clicks on
an HTML element, i.e., when a user clicks on an image, button, or a link.
(c ) Form
Submission Events-These events get triggered when we submit a form.
EXAMPLE OF WITHOUT DHTML:- ( Now let's look into an example of how DHTML can create an impact. For instance, consider a web page that has a list of checkboxes. Now user can select items by checking the corresponding checkboxes and able to submit the selected items. )
(WRITE THIS PROGRAM
IN NOTE PAD OR ANY OTHER EDITOR)
NOW IF WE WANT TO
IMPLEMENT THIS FEATURE WITHOUT DHTML, THE CODE WOULD LOOK SOMETHING LIKE THIS:
In the example below, if we
want to select all the items, we would have to select all the items
individually. We can also see that it has no styling.
SAVE FILE :
withouthtml.html
<!DOCTYPE html>
<html>
<head>
<title>EXAMPLE WITHOUT DHTML</title>
</head>
<body>
<h1>Skills</h1>
<ul>
<li>
<input type="checkbox"
name="item1" value="Full Stack
Developer" />Full Stack
Developer
</li>
<li>
<input type="checkbox"
name="item2" value="Front-end Developer" />Front-end
Developer
</li>
<li>
<input type="checkbox"
name="item3" value="Back-end Developer" />Back-end
Developer
</li>
<li>
<input type="checkbox"
name="item4" value="Blockchain Developer" />Blockchain
Developer
</li>
<li>
<input type="checkbox"
name="item5" value="Game Developer" />Game Developer
</li>
</ul>
<input id=”submit-button”
type="submit" value="Submit" />
</body>
</html>
OUTPUT
EXAMPLE PROGRAM OF
WITH DHTML WITH JAVASCRIPT (To change the Text after click, To change the color
after click, To hide the text after click.) (WRITE THIS PROGRAM IN NOTE PAD OR
ANY OTHER EDITOR)
FILE SAVE: FILE_NAME.HTML
e.g :- ABC.HTML
<!DOCTYPE html>
<html>
<head>
<title>Dynamic HTML
Example</title>
<style>
body {
text-align: center;
font-family: Arial;
margin-top: 50px;
}
#myText {
font-size: 24px;
color: blue;
}
button {
padding: 10px 20px;
font-size: 16px;
}
</style>
</head>
<body>
<h1>Dynamic HTML with
JavaScript</h1>
<p id="myText">Hello
Student!</p>
<button
onclick="changeText()">Click Me</button>
<button
onclick="changeColor()">Change Color</button>
<button
onclick="hideText()">Hide Text</button>
<script>
function changeText() {
document.getElementById("myText").innerHTML = "Text
Change Ho Gaya!";
}
function changeColor() {
document.getElementById("myText").style.color
= "red";
}
function hideText() {
document.getElementById("myText").style.display =
"none";
}
</script>
</body>
</html>
OUTPUT
WHAT IS AJAX:- AJAX is not a programming language.
Full form AJAX (Asynchronous
JavaScript and XML, ASYNCHRONOUSLY MEANS IN AJAX MEANS WEB PAGES CAN REQUEST
DATA FROM A SERVER IN THE BACKGROUND AND UPDATE PARTS OF A PAGE WITHOUT
RELOADING THE ENTIRE PAGE.
Example of Usage:-
(1) Live Search Results:- Search suggestions appear as you type
without reloading the page,
(2) Form Submission:- Submitting form data or liking a post without
refreshing, notes this YouTube video.
(3) Infinite Scrolling:- Loading new content automatically as you
scroll down a page, as mentioned in this YouTube video.
(4) Real-time Updates:- Updating stock prices or live scores, as
discussed in this YouTube video.
( Meaning or explanation :- Imagine browsing a
website and being able to submit a form, load new content, or update
information without having to refresh the entire page. That's the magic of
AJAX. Asynchronous JavaScript and XML (AJAX) is a web development technique
that allows web pages to communicate with a web server asynchronously, meaning
it can send and receive data in the background without interfering with the
user's interaction on the page. )
( EXPLANATION :-
AJAX stands for Asynchronous Javascript and
XML. So what does that mean? XML is a document formatting language. It's main
benefit is that it stores data in such a way that both humans and computers can
easily read it. Javascript is a web scripting language used to give some level
of logic to an HTML page (HTML itself is only a layout language for displaying
static data). Asynchronous is the important part of
AJAX. Traditionally you load a web page all at the same time (right when
you first click a link or type in an address). AJAX allows for delaying in
loading parts of that data until some later time, usually based on user
actions.
Here is an example. Let's say
you want to display a big table worth of information, and it's more information
than is easily displayed on one screen. What you usually do is paginate the
data (break the data into pages with next/previous, and usually 1,2,3...8,9
style page links). If you were going to do this in straight HTML then clicking
on the Next button would just be a link to a entirely new HTML document that
causes the web browser to reload the entire page. This isn't great as it's
visually distracting and can take a significant amount of time, especially
since a good portion of what you are reloading isn't changing. Instead of that
you could use HTML with javascript. In this case you could load all the pages
of information into memory, and when you click the Next button, javascript
replaces just the content that needs replacing. This is faster, and visually
cleaner, but if there is a lot of data it could take a long time to load the
page in the first place, and wastes memory space holding all the content (most
of which isn't being displayed at any given time). The
AJAX solution is to only load the currently displayed data, and when you click
the Next button it issues an AJAX call to go fetch the new pages data you need,
and then update just the portion of the display that needs updating. )
DEFINITION :- AJAX stands for asynchronous Javascript and XML. AJAX
is not a programming language or technology, but it is a combination of
multiple web-related technologies like HTML, XHTML, CSS, JavaScript, DOM, XML,
XSLT and XMLHttpRequest object. The AJAX model allows web developers to create
web applications that are able to dynamically interact with the user. It will
also be able to quickly make a background call to web servers to retrieve the
required application data. Then update the small portion of the web page
without refreshing the whole web page.
AJAX applications are much more
faster and responsive as compared to traditional web applications. It creates a
great balance between the client and the server by allowing them to communicate
in the background while the user is working in the foreground.
In the AJAX applications, the
exchange of data between a web browser and the server is asynchronous means
AJAX applications submit requests to the web server without pausing the
execution of the application and can also process the requested data whenever
it is returned. For example, Facebook uses the AJAX model so whenever we like
any post the count of the like button increase instead of refreshing the whole
page.
Ajax is made up of
the following technologies:-
i.
Javascript:- It is an important part of AJAX. It allows
you to create client-side functionality. or we can say that it is used to
create AJAX applications.
ii. XML:- It is
used to exchange data between web server and client.
iii. The XMLHttpRequest:-
It is used to perform asynchronous data exchange between a web browser
and a web server.
iv. HTML and CSS:- It
is used to provide markup and style to the webpage text.
v. DOM:- It is
used to interact with and alter the webpage layout and content dynamically.
Advantages of AJAX:-
(1) It creates responsive and interactive web applications.
(2) It supports the development of patterns and frameworks that
decrease the development time.
(3) It makes the best use of existing technology and feature
instead of using some new technology.
(4) It makes an asynchronous call to the web server which means
the client doesn't have to wait for the data to arrive before starting
rendering.
Disadvantages of
AJAX:-
(1) AJAX is fully dependent on Javascript.
So if anything happens with javascript in the browser AJAX will not support.
(2) The debugging of AJAX applications is difficult.
(3) Bookmarking of AJAX-enabled pages required pre-planning.
(4) If one request can fail then it can fail the load of the
whole webpage.
(5) If JavaScript is disabled in your web
browser then you are not able to run the AJAX webpage.
EXAMPLE OF AJAYX PROGRAM WITH JAVA SCRIPT, to make a request
to a server and retrieve data. Means simple display a message :-
SAVE FILE:- FILE_NAME.HTML (USE
NOTE PAD OR ANY OTHER EDITOR)
AJAYX.HTML
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>The XMLHttpRequest
Object</h2>
<button
type="button" onclick="loadDoc()">DR. AJAY KUMAR PATHAK,
Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 &&
this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt",
true);
xhttp.send();
}
</script>
</body>
</html>
OUTPUT
NOW I AM EXPLAINING
Example WHICH IS USED ABOVE CODE
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this
text</h2>
<button type="button"
onclick="loadDoc()">Change Content</button>
</div>
</body>
</html>
(a) The HTML page contains a <div> section and a
<button>.
(b) The <div> section is used to display information from a
server.
( c) The <button> calls a function (if it is clicked).
(d) The function requests data from a web server and displays it:
And rests are the JavaScript
codes.
AJAX - TYPES OF
REQUESTS / METHODS :-
AJAX supports threwe
types of requests and they are:-
(1) GET request
(2) POST request
(3) PUT request
(3) DELETE request
(1) GET request:- The GET request is used to retrieve data from a
server. In this request, the data is sent as a part of the URL that is appended
at the end of the request. We can use this request with the open() method
Where, the open() method takes
three parameters −
(a) GET:- It is used to retrieve data from the server.
(b) url:- url represents the file that will be opened on
the web server.
(c ) true
− For asynchronous connection set the value to true. Or for synchronous
connection set the value to false. The default value of this parameter is true.
(2) POST request:- The POST request is used to send data from a web page
to a web server. In this request, the data is sent in the request body that is
separated from the URL. We can use this request with the open() method.
Syntax:- open('POST', url,
true)
Where, the open() method takes
three parameters −
(a) POST:- It is used to send data to the web server.
(b) url:- url represents the server(file) location.
(c ) true:- For asynchronous connection set the
value to true. Or for synchronous connection set the value to false. The
default value of this parameter is true.
(3) PUT request:- Through PUT request we can updating the record on server .
(4) DELETE request:- The DELETE request is used to delete data from the
web server. In this request, the data to be deleted is sent in the request body
and the web server will delete that data from its storage.
Syntax:-
open('DELETE', url, true)
Where, the open() method takes
three parameters:-
(a) DELETE:- It is used to delete data from the web server.
(b) url:- It represents the file url which
will be opened on the web server. Or we can say server(file) location.
(c ) true:- For asynchronous connection set the value to true. Or for
synchronous connection set the value to false. The default value of this
parameter is true.
TYPES OF AJAX:-
(1) ASYNCHRONOUS AJAX
(2) SYNCHRONOUS AJAX:-
AJAX can access the server both
synchronously and asynchronously:
Synchronously:-, Synchronously
in which the JavaScript stops and waits for the server to send back a reply
before continuing.
(MEANS:- Synchronously AJAX , sinkronas prakriya mein, jaavaaskript ruk jaatee hai aur aage badhane se pahale sarvar se javaab aane ka intajaar karatee hai.
Asynchronously, in which the
script allows the page to continue to be processed and handles the reply if and
when it arrives.
( Synchronous Ajax request is the process in
which execution of the request stops until a response is received and Asynchronous
Ajax request means the script continue the process without waiting for the
server to reply. It will handle the reply if it arrives.
Ajax principle is simple to
send an asynchronous request to the server object is to obtain data from the
server, and then use javascript to manipulate the DOM (Document
Object Model. The HTML DOM (Document Object Model) is a structured
representation of a web page that allows developers to access, modify, and
control its content and structure using JavaScript. ) and update the page. This is the most
critical step is to obtain the requested data from the server.
By default, Ajax request is
Asynchronous but sometimes you need to send your request synchronously )
INTRODUCTION TO JAVA
BEANS:-
( Meaning only:- JavaBeans is a
technology developed by Sun Microsystems (now Oracle) and released in 1996, as
part of JDK 1.1.
The 'beans' of JavaBeans are
classes that encapsulate one or more objects into a single standardized object
(the bean). This standardization allows the beans to be handled or, allowing
easier code reuse and introspection (In computing, type introspection is the
ability of a program to examine the type or properties of an object at runtime.
Some programming languages possess this capability.) . This in turn allows the
beans to be treated as software components, and to be manipulated visually by
editors and IDEs without needing any initial configuration, or to know any
internal implementation details.)
Definition:- JavaBeans (thereafter referred to as beans) are
reusable software components that are written in the Java programming language
and can be manipulated by using beans-aware builder tools. Because the beans
are reusable, you can use them to construct more complex components, build new
applications, or add functionality to existing applications. You can interact
with beans visually, by using a builder, or manually, by calling the beans
methods from a program.
Beans define a design-time
interface that allows application builder tools to query components to
determine the kinds of properties these components define and the kinds of
events they generate (or to which they respond). You do not need to use special
introspection and construction tools when working with beans. The pattern
signatures are defined and can be easily recognized and understood by visual
inspection.
Rules of JavaBeans
(Very Important):-
A class is called a
JavaBean only if it follows these rules:
i.
Class must be
public
ii. Must have a no-argument constructor
iii. Properties (variables) must be private
iv. Provide public getter and setter methods
v. Should implement Serializable (optional but
recommended)
You can write
JavaBeans programs in:
Software Options:- Eclipse IDE
(Best for beginners) or NetBeans or IntelliJ
IDEA or
Notepad + Command Prompt (Basic
method)
How to Write
JavaBeans Program (Easy Steps):- Follow these steps:
Step 1: Create a class (Bean
class), Write class with private variables
Step 2: Add no-argument
constructor
Step 3: Create Getter &
Setter methods
Step 4: (Optional) Implement
Serializable
Step 5: Create another class to
use the bean
How to Run (Using
Command Prompt):-
Step 1: Save files:-
StudentBean.java,
MainClass.java
Step 2: Compile:-
javac StudentBean.java
javac MainClass.java
Step 3: Run:- java MainClass
STRUCTURE OF JAVABEAN:-
A JAVABEAN LOOKS LIKE THIS:-
JAVA PROGRAM:-
public class StudentBean {
private String name;
private int age;
public StudentBean() {
// no-argument constructor
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
NOTE:- EXPLANATION OF PROPERTIES OF JAVA BEAN:-
(1) getName():- For example, if property name is Name, your method name would be
getName() to read that property. This method is called accessor. ( getName() Value
ko read karne ke liye)
(2) setPropertyName():- For example, if property name is Name, your method
name would be setName() to write that property. This method is called mutator.
(setName() Value ko set karne ke liye )
EXAMPLE OUTPUT :- IN JAVA PROGRAM
student.setName("Ajay"); // set value
System.out.println(student.getName());
// get value
FULL JAVABEANS
PROGRAM (STEP-BY-STEP):-
Step 1: Create JavaBean Class
File Name: StudentBean.java
import java.io.Serializable;
public class StudentBean
implements Serializable
{
private String name;
private int age;
public StudentBean() // contractor
{
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
Step 2: Create Main
Class to Use Bean:-
File Name: MainClass.java
public class MainClass {
public static void main(String[] args) {
StudentBean student = new
StudentBean();
student.setName("Ajay");
student.setAge(20);
System.out.println("Name: " +
student.getName());
System.out.println("Age: " +
student.getAge());
}
}
OUTPUT
Name: Ajay
Age: 20
TYPES OF JAVA BEANS
:-
(1) JavaBeans (Standard Beans):-
·
Traditional
reusable software components in Java.
·
Must follow
conventions: private fields, public getters/setters, no-arg constructor, and
implement Serializable ((serialized means, Java Beans can be saved and
restored. )
·
Widely used in
JSP (JavaServer Pages. It is a server-side technology used to create dynamic,
platform-independent web applications by embedding Java code directly into HTML
or XML files. As of 2023, it is also referred to as Jakarta Server Pages) pages, desktop applications, and early Java
frameworks.
(2) Enterprise JavaBeans (EJB):-
·
Part of the Java
EE (Jakarta EE) specification.
·
Server-side
components that encapsulate business logic.
·
Types of EJB:
Session Beans (Stateless, Stateful, Singleton), and Message-Driven Beans
·
Provide services
like transactions, security, persistence, and scalability.
·
Commonly used in
enterprise-scale applications.
(3) Spring Beans:-
·
Managed objects
in the Spring Framework container.
·
Defined via XML
configuration, annotations (@Component, @Bean), or Java-based configuration.
·
The Spring IoC
(Inversion of Control) container manages the lifecycle and dependencies of
these beans.
·
Used heavily in
modern enterprise applications.
Why Java Bean use?:-
i.
A fundamental
principle of software development is “Don’t Repeat Yourself” (DRY); a JavaBean
is a reusable software component that can be used all around a Java
application, adhering to the DRY principle.
ii. Java is an Object-Oriented Programming (OOP) Language.
A core concept of OOP is encapsulation. A JavaBean encapsulates many objects
into a single object (the bean).
iii. We can expose JavaBean events, properties, and methods
to another application.
iv. Even though JavaBeans are designed to run on the
client-side, one can develop server-side beans.
Advantages of Java
Beans :-
(1) Reusability:- JavaBean is designed to be a reusable component
that can be easily integrated into other applications, which can save
development time and effort.
(2) Encapsulation:- JavaBean encapsulates data and behavior, which
helps to keep the code modular and easy to maintain. This makes it easier to
modify and extend the code without affecting other parts of the system.
(3) Standardization:- JavaBean follows a set of conventions and standards,
which makes it easier to understand and work with code written by others.
(4) Compatibility:- JavaBean is compatible with a wide range of
Java technologies and frameworks, which makes them highly versatile and
adaptable to different types of projects.
(5) Persistence:- JavaBeans can be serialized (serialized means, Java
Beans can be saved and restored. ) and stored on a disk or sent over the
network, which makes it easy to save and load data in a standardized format.
(6) Integration:- JavaBean can be easily integrated into different
Java-based technologies and architectures, such as JavaServer Faces, Spring, or
Java EE, which makes them highly flexible and compatible.
(7) Platform independence:- JavaBean can run on any platform that
supports the Java Virtual Machine. This makes it highly portable and
platform-independent.
Disadvantages of Java
Beans:-
(1) Complexity:- JavaBean
can be complex to develop and maintain, especially if they have a lot of
properties and methods. This complexity can lead to longer development times
and an increased risk of bugs.
(2) Limited functionality:- JavaBean is primarily designed to
encapsulate data. It can also include behavior through methods. It is not
well-suited for more complex tasks such as multithreading, networking, or user
interface programming.
(3) Lack of flexibility:- JavaBean is designed to use as a
standalone component. This means that it can be limited in its ability to
interact with other components and systems.
(4) Tight coupling:- JavaBean can introduce tight coupling between
components. This makes it difficult to modify or extend the system in the
future.
JDBC DATABASE CONNECTIVITY WITH MYSQL:-
JDBC (Full form JAVA DATABASE
CONNECTIVITY) is an API that helps applications to communicate with databases.
It allows Java programs to connect to a database, run queries, retrieve and
manipulate data. Because of JDBC, Java applications can easily work with
different relational databases like MySQL, Oracle, PostgreSQL and more.
When you are using JDBC outside
of an application server, the DriverManager class manages the
establishment of connections.
Specify to
the DriverManager which JDBC drivers to try to make Connections with.
The easiest way to do this is to use Class.forName() on the class
that implements the java.sql.Driver interface. With MySQL Connector /
J, the name of this class is com.mysql.cj.jdbc.Driver. With this method,
you could use an external configuration file to supply the driver class name
and driver parameters to use when connecting to a database.
The programming involved to
establish a JDBC connection is fairly simple. Here are these simple three steps:-
(1) Import JDBC Packages:- Add
import statements to your Java program to import required classes in your Java
code.
(2) Database URL Formulation:- This
is to create a properly formatted address that points to the database to which
you wish to connect.
(3) Create Connection Object:- Finally, code a call to the
DriverManager object's getConnection( ) method to establish actual database
connection.
Import JDBC Packages:-
The Import statements tell the Java
compiler where to find the classes you reference in your code and are placed at
the very beginning of your source code.
To use the standard JDBC
package, which allows you to select, insert, update, and delete data in SQL
tables, add the following imports to your source code:-
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for
BigDecimal and BigInteger support
Register JDBC
Driver:- You must have the required JDBC
driver in the classpath. In current case, you set CLASSPATH variable to
C:\Program
Files\MySQL\mysql-connector-java-5.1.8\mysql-connector-java-5.1.8-bin.jar. Your
driver version may vary based on your installation.
Database URL
Formulation:- After you've loaded the
driver, you can establish a connection using the DriverManager.getConnection()
method. For easy reference, let me list the three overloaded
DriverManager.getConnection() methods:-
·
getConnection(String
url)
·
getConnection(String
url, Properties prop)
·
getConnection(String
url, String user, String password)
Here each form requires a
database URL. A database URL is an address that points to your database.
Formulating a database URL is
where most of the problems associated with establishing a connection occurs.
Following table lists down the
MySQL JDBC driver name and database URL.
|
RDBMS |
JDBC driver name |
URL format |
|
MySQL |
com.mysql.jdbc.Driver |
jdbc:mysql://hostname/ databaseName |
All the highlighted part in URL
format is static and you need to change only the remaining part as per your
database setup.
Create Connection
Object:- We have listed down three forms
of DriverManager.getConnection() method to create a connection object.
Using a Database URL
with a username and password:-
The most commonly used form of
getConnection() requires you to pass a database URL, a username, and a password
−
As you are using MySQL driver,
you'll specify a host:port:databaseName value for the database portion of the
URL.
If you have a host at TCP/IP
address 192.0.0.1 with a host name of localhost, and your MySQL listener is
configured to listen on port 3306 as default, and your database name is AJAYCLASS,
then complete database URL would be:-
jdbc:mysql://localhost/ AJAYCLASS
Now you have to call
getConnection() method with appropriate username and password to get a
Connection object as follows :-
String URL =
"jdbc:mysql://localhost AJAYCLASS ";
String USER =
"guest";
String PASS =
"password"
Connection conn =
DriverManager.getConnection(URL, USER, PASS);
Using a Database URL
and a Properties Object:- A third form of
the DriverManager.getConnection( ) method requires a database URL and a
Properties object:-
DriverManager.getConnection(String
url, Properties info);
A Properties object holds a set
of keyword-value pairs. It is used to pass driver properties to the driver
during a call to the getConnection() method.
To make the same connection
made by the previous examples, use the following code:-
import java.util.*;
String URL =
"jdbc:mysql://localhost/TUTORIALSPOINT";
Properties info = new
Properties( );
info.put( "user",
"guest" );
info.put( "password",
"guest123" );
Connection conn =
DriverManager.getConnection(URL, info);
Now let us compile
the above example as follows
C:\>javac
FirstExample.java
C:\>
When you run
FirstExample, it produces the following result:-
C:\>java FirstExample
ID: 100, Age: 18, First: Anshu,
Last: Singh
ID: 101, Age: 25, First: Sushma,
Last: Behra
ID: 102, Age: 30, First: Sandip,
Last: Nandi
ID: 103, Age: 28, First: Deepak,
Last: Jha
C:\>
FULL STEP-BY-STEP
GUIDE (JDBC + MySQL)
STEP 1: Install Required Software
You need:-
Java (JDK installed)
MySQL Server + MySQL Workbench
MySQL Connector/J (JDBC Driver)
Download JDBC Driver:- Search:
mysql-connector-j download
STEP 2: Create Database & Table in MySQL
Open MySQL Workbench or Command
Prompt
Create Database:- SQL> CREATE
DATABASE studentdb;
Use Database:- SQL> USE studentdb;
Create Table;-
SQL> CREATE TABLE students (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
age INT
);
Now your table is ready.
STEP 3: Create Java Project:-
You can use:- Notepad (simple)
or IDE like Eclipse / NetBeans
(recommended)
STEP 4: Add JDBC Driver:- If using Eclipse:- Right click
project,
Build Path → Configure Build
Path, Add External JARs, Select mysql-connector-j.jar
STEP 5: Write JDBC Program:- Java Program Example:-
JAVA PROGRAM
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
try {
// 1. Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Create Connection
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/studentdb",
"root",
"password"
);
// 3. Create Statement
Statement stmt =
con.createStatement();
// 4. Insert Data
String query = "INSERT INTO
students(name, age) VALUES('Ajay', 21)";
stmt.executeUpdate(query);
System.out.println("Data
Inserted Successfully!");
// 5. Close Connection
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
STEP 6: Save File:- Save file as:- JDBCExample.java
Make sure:- File name = Class
name, Save inside a folder (like jdbc_project)
STEP 7: Compile & Run:- Compile, javac JDBCExample.java
Run:- java JDBCExample
STEP 8: Check Output:- Go to MySQL and run:-
SELECT * FROM students;
You will see inserted data.
WHAT IS SERVLETS
SERVLETS:-
What Is a Servlet?:- (Simple
words , Servlet = Java program used to create dynamic web pages, Example:- When
you fill a form on a website → data goes to server → Servlet processes it →
sends response back.)
A servlet is a Java programming
language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model.
Although servlets can respond to any type of request, they are commonly used to
extend the applications hosted by web servers (e.g. Apache Tomcat or any other
like Apache HTTP Server, Nginx, Microsoft Internet Information Services (IIS),
and LiteSpeed Web Server.). For such applications, Java Servlet technology
defines HTTP-specific servlet classes.
They are used to handle the
request obtained from the web server, process the request, produce the response,
then send a response back to the webserver
The javax.servlet and
javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines
life-cycle methods. When implementing a generic service, you can use or extend
the GenericServlet class provided with the Java Servlet API. The HttpServlet
class provides methods, such as doGet and doPost, for handling HTTP-specific
services.
Properties of Servlets are as
follows:-
• Servlets work on the
server-side.
• Servlets are capable of
handling complex requests obtained from the webserver.
Servlet Architecture
is can be depicted from the image itself as provided below as follows OR Servlet
Architecture Workflow::-
OR Servlet
Architecture Workflow
Execution of Servlets basically
involves seven basic steps:
1. The clients send the request
to the webserver.
2. The web server receives the
request.
3. The web server passes the
request to the corresponding servlet.
4. The servlet processes the
request and generates the response in the form of output.
5. The servlet sends the
response back to the webserver.
6. The web server sends the
response back to the client and the client browser displays it on the screen
7. Web Container:- Also known as Servlet Container
and Servlet Engine. It is a part of Web Server that interacts with Servlets.
This is the main component of Web Server that manages the life cycle of
Servlets.
How Servlet Works?:-
1) When the web server (e.g. Apache Tomcat) starts up, the
servlet container deploy and loads all the servlets. During this step Servlet
container creates ServletContext object. ServletContext is an interface that
defines the set of methods that a servlet can use to communicate with the
servlet container.
Note: There is only one
ServletContext per webapp which is common to all the servlets. ServletContext
has several useful methods such as addListener(), addFilter() etc.
2) Once the servlet is loaded, the servlet container creates the
instance of servlet class. For each instantiated servlet, its init() method is
invoked.
3) Client (user browser) sends an Http request to web server on a
certain port. Each time the web server receives a request, the servlet
container creates HttpServletRequest and HttpServletResponse objects. The
HttpServletRequest object provides the access to the request information and
the HttpServletResponse object allows us to format and change the http response
before sending it to the client.
The servlet container spawns
(create) a new thread that calls service() method for each client request. The
service() method dispatches the request to the correct handler method based on
the type of request.
For example if server receives
a Get Request the service() method would dispatch the request to the doGet() method
by calling the doGet() method with request parameters. Similarly the requests
like Post, Head, Put etc. are dispatched to the corresponding handlers
doPost(), doHead(), doPut() etc. by service() method of servlet.
Life Cycle of Servlet:-
Servlet life cycle
contains five steps:-
1) Loading of Servlet
2) Creating instance of Servlet
3) Invoke init() once
4) Invoke service() repeatedly
for each client request
5) Invoke destroy()
Step 1: Loading of
Servlet:- When the web server (e.g.
Apache Tomcat) starts up, the servlet container deploy and loads all the
servlets.
Step 2: Creating
instance of Servlet:- Once all the
Servlet classes loaded, the servlet container creates instances of each servlet
class. Servlet container creates only once instance per servlet class and all
the requests to the servlet are executed on the same servlet instance.
Step 3: Invoke init()
method:- Once all the servlet classes are
instantiated, the init() method is invoked for each instantiated servlet. This
method initializes the servlet. There are certain init parameters that you can
specify in the deployment descriptor (web.xml) file.
For example, if a servlet has
value >=0 then its init() method is immediately invoked during web container
startup.
You can specify the element in
web.xml file like this:
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.beginnersbook.MyServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Now the init() method for
corresponding servlet class com.beginnersbook.MyServletDemo would be invoked
during web container startup.
Note: The init() method is called only once during the life
cycle of servlet.
Step 4:- Invoke service() method:- Each time the web server
receives a request for servlet, it spawns (create) a new thread that calls
service() method. If the servlet is GenericServlet then the request is served
by the service() method itself, if the servlet is HttpServlet then service()
method receives the request and dispatches it to the correct handler method
based on the type of request.
For example if its a Get
Request the service() method would dispatch the request to the doGet() method
by calling the doGet() method with request parameters. Similarly the requests
like Post, Head, Put etc. are dispatched to the corresponding handlers
doPost(), doHead(), doPut() etc. by service() method of servlet.
Step 5:- Invoke destroy() method:- When servlet container
shuts down(this usually happens when we stop the web server), it unloads all
the servlets and calls destroy() method for each initialized servlets.
STEP-BY-STEP: HOW TO
CREATE A SERVLET PROGRAM
Step 1:- Install Required Software
You need 3 things:- Java JDK
(Install Java), Apache Tomcat Server (Servlet container), IDE (optional but
helpful) → Eclipse / VS Code / Notepad ( Best for beginners: Eclipse IDE)
Step 2: Folder Setup
(Important):- If you are NOT using
Eclipse, follow this:-
(a) Go to Tomcat folder:- apache-tomcat/webapps/
(b) Create your project folder:- MyApp/
(c ) Inside
it create:-
MyApp/
WEB-INF/
web.xml
classes/
Step 3:- Write Your First Servlet Program:- Create a file:-
File name: HelloServlet.java
Save location:- WEB-INF/classes/
Code:-
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet
extends HttpServlet {
public void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Ajay!
This is your first Servlet</h1>");
out.println("</body></html>");
}
}
Step 4:- Compile the Servlet:-
Open command prompt in classes
folder and run:-
javac -cp
"C:\apache-tomcat\lib\servlet-api.jar" HelloServlet.java
This creates:- HelloServlet.class
Step 5:- Configure web.xml:-
Location:- WEB-INF/web.xml
Code:-
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Step 6:- Start Tomcat Server
(a) Go to:- apache-tomcat/bin/
(b) Run:- startup.bat
(c ) Server
starts
Step 7:- Run Your Servlet in Browser:-
Open browser and type:- http://localhost:8080/MyApp/hello
OUTPUT:- Hello Ajay! This is
your first Servlet
Types of Servlet
Methods:-
|
Method |
Use |
|
doGet() |
For fetching
data |
|
doPost() |
For sending data
(forms) |
ADVANTAGES OF JAVA
SERVLETS:-
(1) Portability:- As we know that the servlets are written in java and
follow well known standardized APIs so they are highly portable across
operating systems and server implementations. We can develop a servlet on
Windows machine running the tomcat server or any other server and later we can
deploy that servlet effortlessly on any other operating system like Unix server
running on the iPlanet/Netscape Application server. So servlets are write once,
run anywhere (WORA) program.
(2) Powerful:- We can do several things with the servlets which were difficult or
even impossible to do with CGI, for example the servlets can talk directly to
the web server while the CGI (Common Gateway Interface ) programs can’t do.
Servlets can share data among each other, they even make the database
connection pools easy to implement. They can maintain the session by using the
session tracking mechanism which helps them to maintain information from
request to request. It can do many other things which are difficult to
implement in the CGI programs.
(3) Efficiency:- As compared to CGI the servlets invocation is highly
efficient. When the servlet get loaded in the server, it remains in the
server’s memory as a single object instance. However with servlets there are N
threads but only a single copy of the servlet class. Multiple concurrent
requests are handled by separate threads so we can say that the servlets are
highly scalable.
(4) Safety:- As servlets are written in java, servlets inherit the strong type
safety of java language. Java’s automatic garbage collection and a lack of
pointers means that servlets are generally safe from memory management
problems. In servlets we can easily handle the errors due to Java’s exception
handling mechanism. If any exception occurs then it will throw an exception.
(5) Integration:-Servlets are tightly integrated with the server.
Servlet can use the server to translate the file paths, perform logging, check
authorization.
(6) Extensibility;- The servlet API is designed in such a way that it can
be easily extensible. As it stands today, the servlet API support Http
Servlets, but in later date it can be extended for another type of servlets.
(7) Inexpensive:- There are number of free web servers available for
personal use or for commercial purpose. Web servers are relatively expensive.
So by using the free available web servers you can add servlet support to it.
Disadvantages of
servlet:-
(1) Designing in servlet is difficult and slows down the
application.
(2) Writing complex business logic makes the application difficult
to understand.
(3) You need a Java Runtime Environment on the
server to run servlets. CGI (Common Gateway Interface). is a completely
language independent protocol, so you can write CGIs in whatever languages you
have available (including Java if you want to).
Advantages
over CGI
(1) The advantages of using Servlets are their
fast performance and ease of use combined with more power over traditional CGI
(Common Gateway Interface). Traditional CGI scripts written in Java have a
number of disadvantages when it comes to performance:
(2) When an HTTP request is made, a new
process is created for each call of the CGI script. This overhead of process
creation can be very system-intensive, especially when the script does
relatively fast operations. Thus, process creation will take more time than CGI
script execution. Java Servlets solve this, as a Servlet is not a separate
process. Each request to be handled by a Servlet is handled by a separate Java
thread within the web server process.
(3) Simultaneous CGI request causes the CGI
script to be copied and loaded into memory as many times as there are requests.
However, with Servlets, there are the same amount of threads as requests, but
there will only be one copy of the Servlet class created in memory that stays
there also between requests.
(4) Only a single instance answers all
requests concurrently. This reduces memory usage and makes the management of
persistent data easy.
(5) A Servlet can be run by a Servlet
container in a restrictive environment, called a sandbox. This is similar to an
applet that runs in the sandbox of the web browser. This makes a restrictive
use of potentially harmful Servlets possible.
WHAT IS JSP:-
(1ST OF ALL , WHY
USE JSP 1ST KNOW:-
(1) First Understand: What is Servlet?:-A Servlet is a Java program
that runs on a server and handles requests from users.
Example (Servlet):-
SAVE IN JAVA PROGRAME
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet
extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException {
PrintWriter out = res.getWriter();
out.println("<html><body>");
out.println("<h1>Hello
User!</h1>");
out.println("</body></html>");
}
}
OUTPUT:- When you run this, it
shows Hello User! in browser.
(2) 2. Problem with Servlet (IMPORTANT ):-
Servlet works fine BUT…, If you want to design a webpage (HTML USER
INTERFACE ), it becomes very messy (untidy)
Example:-WRITE JAVA PROGRAM
out.println("<html>");
out.println("<body>");
out.println("<h1>Welcome</h1>");
out.println("</body>");
out.println("</html>");
Imagine writing full
website like this , Too many out.println() → hard to read, write, and maintain.
NOTE:- Problem with Servlet (Main Reason JSP Exists), Look
carefully,
You are writing HTML CODE IN
JAVA like this in HTML (THIS IS CODE OF HTML BUT WRITING IN JAVA): out.println("<h1>Hello</h1>");
Problem:-
Too many out.println()
Hard to read
Hard to design big pages
Mixing Java + HTML = confusing
(3) NOW INSTEAD OF SERVLETS WE CAN USE JSP, What is JSP?
JSP (JavaServer Pages) is used
to create web pages easily using HTML + Java., In JSP, you write HTML normally, and add
Java code when needed.
(4) Same Example using JSP (VERY EASY)
PROGRAM OF JSP:- (
<html>
<body>
<h1>Hello
User!</h1>
</body>
</html>
NOTE SEE- That’s it! No
out.println() needed , No Java printing needed , Much cleaner and easy.
DEFINITION OF JSP :- Formerly known as Java Server Pages, Jakarta Server Pages (JSP) is a Java-based collection
of technologies that allow you to write data-driven web content and insert Java
into HTML pages.
JavaServer Pages (JSP) is a
server-side technology that creates dynamic web applications. It allows
developers to embed Java code directly into HTML pages and it makes web
development more efficient. JSP is an advanced version of Servlets. It provides
enhanced capabilities for building scalable and platform-independent web pages.
It combines writing markup with
back-end interaction and creates JSP tags (either with HTML or XML) with JSP
Actions and commands. When conceptualising JSP, you can consider it an
extension of HTML programming. JSP allows you to modify HTML pages by embedding
Java code, making it possible to create content that will change based on
factors such as the date, time, and user input.
Once you translate this code
into a Jakarta Servlet, you can execute it within the platform. You couldn’t do
otherwise because HTTP servers cannot directly run Java web applications.
Otherwise, you would have to forward Java applications to Java application
servers. However, with JSPs, you can streamline the process and make it more
straightforward.
Where to Write JSP
Program?:- You can write JSP in:- Notepad (simple), Notepad++, VS Code, Eclipse IDE (best for beginners) (For now,
use Notepad or VS Code (easy)
JSP File Extension:- JSP files always have this extension:- .jsp
Example:-
index.jsp
login.jsp
hello.jsp
Basic Syntax of JSP:- A JSP
page looks like HTML but can include Java code.
JSP PROGRAM
Simple JSP Syntax Example:
<html>
<head>
<title>My First JSP</title>
</head>
<body>
<h1>Hello
World</h1>
<%
out.println("This :-is Java code
inside JSP");
%>
</body>
</html>
Important JSP Tags:-
|
Tag |
Meaning |
|
<%
%> |
Java
code |
|
<%=
%> |
Print
output |
|
<%@
%> |
Page
directive |
Example using all
tags:-
Jsp program save:-
file_name.jsp (use note pad)
<%@
page language="java" %>
<html>
<body>
<%
String name = "Ajay";
%>
<h2>Hello <%= name %></h2>
</body>
</html>
How to Save JSP File (JSP FILE ONLY WITHOUT HTML):-
Step-by-step:- Open Notepad, Write JSP code, Click File →
Save As,
In "File name" →
type:-
Save file:- hello.jsp
In "Save as type" →
select:
All Files (*.*)
How to Run JSP
Program (IMPORTANT)
JSP cannot run directly like
Java → needs Server:-
You need:- Apache Tomcat Server
Step-by-step to Run JSP
STEP 1: Install Tomcat
Download and install Apache
Tomcat
STEP 2: Start Server:- Go to Tomcat folder, Open, bin → startup.bat,
Server will start
STEP 3: Place JSP File, Put your file in,
webapps/myproject/hello.jsp
STEP 4: Open Browser, Type, http://localhost:8080/myproject/hello.jsp
OUTPUT:- Hello World, This is
Java code inside JSP
FULL EXAMPLE PROGRAM:-
FILE NAME:- hello.jsp
<html>
<body>
<h1>My First JSP
Page</h1>
<%
int a = 10;
int b = 20;
int sum = a + b;
out.println("Sum = " + sum);
%>
</body>
</html>
OUTPUT:- My First JSP Page
Sum = 30
2ND
EXAMPLE:- (VERY FIRST STEP)
(1) Before
writing JSP, you must install:
(a) Java (JDK), JSP runs on Java, so install JDK
(b) Apache Tomcat (Server), JSP cannot run alone, it needs a server
(2) Folder
Setup (IMPORTANT), After installing Tomcat, you will see a folder like
C:\apache-tomcat-10\
Inside it:- webapps ← (VERY IMPORTANT FOLDER)
(3) Where to
Create JSP File?:- Go inside, C:\apache-tomcat-10\webapps\ , Now
create a new folder, myproject,
Final path:- C:\apache-tomcat-10\webapps\myproject\
(4) Write
JSP Program:- Step-by-step:- Open Notepad,
Write this code:-
<html>
<body>
<h1>This is my first JSP
page</h1>
<%
out.println("Hello Ajay, this is JSP
running!");
%>
</body>
</html>
(5) Save JSP
File:- VERY IMPORTANT:-
Click File → Save As, File
name:- hello.jsp, Save as type:- All Files (*.*)
(6) Save in
this folder:- C:\apache-tomcat-10\webapps\myproject\
(7) How
to Start Server (Tomcat):- Go to:- C:\apache-tomcat-10\bin\ ,
Double click:- startup.bat, A black window will open → server started
(8) Run JSP
Program:- Open browser (Chrome),
Type this URL:- http://localhost:8080/myproject/hello.jsp
OUTPUT You Will See:-This is my first JSP page, Hello Ajay, this is JSP running!
3RD EXAMPLE
FULL PROGRAM (HTML + JSP)
File Name: index.jsp
<html>
<head>
<title>My JSP Page</title>
</head>
<body>
<h1>Student
Information</h1>
<!-- HTML Form -->
<form
method="post">
Name: <input type="text"
name="username"><br><br>
Age: <input type="text"
name="age"><br><br>
<input type="submit"
value="Submit">
</form>
<hr>
<!-- JSP CODE START -->
<%
String name =
request.getParameter("username");
String age =
request.getParameter("age");
if(name != null && age != null)
{
%>
<h2>Output:</h2>
Name: <%= name %> <br>
Age: <%= age %>
<%
}
%>
</body>
</html>
EXPLANATION (VERY
SIMPLE)
HTML Part;- <form
method="post">
Creates form (HTML) :- <input type="text"
name="username">
User enters name
JSP Part:-
<%
String name =
request.getParameter("username");
%>
Gets value from form
OUTPUT PRINT (JSP) :-
<%= name %>
Print value on
screen:- Shortcut of out.println()
NOW:- Where to Save This File :-
Go to Tomcat folder:- C:\apache-tomcat-10\webapps\
Create folder:- myproject
Save file here:- C:\apache-tomcat-10\webapps\myproject\index.jsp
How to Save File (IMPORTANT);- Open
Notepad, Paste code, Click File → Save As,
File name:- index.jsp, Save as
type:- All Files (*.*)
HOW TO RUN JSP:-
STEP 1: Start Server
Go to:- apache-tomcat-10 → bin
→ startup.bat
STEP 2: Open Browser
Type:- http://localhost:8080/myproject/index.jsp
What You Will See:-
Step 1:-
Form will open,
Enter Name,
Enter Age,
Click Submit
Step 2:- Output will show:-
Output:- Name:- Ajay, Age: 20
JSP ELEMENTS:-
TYPES OF JSP ELEMENTS (MAIN 3)
(1) SCRIPTLET ELEMENT:- Definition:- Scriptlet Element is a JSP element
used to write Java code (statements) inside a JSP page, which is executed when
the page is requested.
Syntax:- <% Java code %>
EXAMPLE:- JSP PROGRAM
<%
int a = 10;
int b = 20;
int sum = a + b;
out.println("Sum is:
" + sum);
%>
OUT:- SUM IS 30
Explanation:- <% %> → Scriptlet block
out.println() → prints output
to browser
(2) EXPRESSION ELEMENT:- Definition:- Expression Element is a JSP element used
to display the result of a Java expression directly on the web page.
Syntax:- <%= expression
%>
EXAMPLE:-
<%
int a = 5;
int b = 3;
%>
Result: <%= a + b %>
Output:- Result: 8
Explanation:-
<%= %> automatically
prints value
Shortcut of out.println()
(3) DECLARATION ELEMENT:- Definition:- Declaration Element is a JSP element used
to declare variables and methods that can be used throughout the JSP page.
Syntax:- <%! declaration
%>
EXAMPLE:-
<%!
int cube(int n){
return n*n*n;
}
%>
Cube of 3 is: <%= cube(3)
%>
Output:-
Cube of 3 is: 27
Explanation:- <%! %> → declare method or variable
Can be used anywhere in page
FULL COMBINED EXAMPLE
:-
<html>
<body>
<h2>JSP Elements
Example</h2>
<%
// Scriptlet
int x = 4;
int y = 6;
int sum = x + y;
%>
<!-- Expression -->
Sum is: <%= sum
%><br>
<%!
// Declaration
int square(int n){
return n*n;
}
%>
Square of 5 is: <%=
square(5) %>
</body>
</html>
OUTPUT:-
JSP Elements Example
Sum is: 10
Square of 5 is: 25
LIFE CYCLE OF JSP:- A
JSP lifecycle can be defined as the process that starts with its creation which
is further translated into a servlet, and then the servlet life cycle comes
into play.
Steps Involved in a JSP
lifecycle:
(1) Translation
(2) Compilation
(3) ClassLoading
(4) Instantiation
(5) Initialization
(6) Request Processing
(7) Destroy
(1) Translation:- This phase deals with the syntactic (proper sentences )
correctness of the page. JSP code is checked by the JSP container and is analyzed
by it to generate the servlet source code. The web container automatically
translates the index.jsp file into index.java.
(2) Compilation :- Here, the JSP container
compiles the JSP class source code. It converts the index.java file into an
index.class file. The translation of the Java source to its implementation
class can occur at any given time between the deployment of the JSP page into
the container and processing of the JSP page.
(3) ClassLoading :- In this phase, the servlet class loaded from the JSP
source is loaded into the container.
(4) Instantiation :- In this phase, an instance of the class is generated.
The container manages one or more instances by responding to the requests.
(5) Initialization :-In this phase, the container invokes the init method
of the JSP class. After that, servlet configuration with the init parameter is
configured. Now, JSP can handle the client requests. Most often, the
translation and initialization in JSP happen as soon as the first request for a
JSP comes.
(6) Request Processing :- This is the most time-consuming phase of the JSP.
Here, the JSP page processes the requests from a client. The request processing
phase is multi-threaded. A new thread is used for every request, and a servlet
request and response object are created. After this, the _jspService() method
is called. This method cannot be overridden.
(7) Destroy :- The last phase of the JSP lifecycle is destroyed. The JSP class is
unloaded or removed from the container in this phase. It is done when the
application is undeployed or when the server is down. This is done using the
jspDestroy() method and can be overridden.
Advantages OF JSP :-
(1) JSP Code cross-platform, write once, run everywhere
(2) JSP Components cross-platform:- JSP components (Enterprise
Javabeans,javabeans or custom JSP tags) are reusable across platforms. The
Enterprise JavaBeans component can access the traditional database and can work
in the Solaris, linux in Distributed system mode. UNIX and Windows platforms.
(3) Support Multiple Web formats:- Currently, JSP technology
supports a Web page format that does not have a clear standard. In general, JSP
technology can not only support html/dhtml traditional browser file format, but
also can support the use of wireless communication devices such as mobile
phones.
(4) JSP Label Extensibility:- Although both ASP and JSP use label
and scripting technology to make Dynamic Web pages, JSP technology allows
developers to extend JSP tags and customize JSP tag libraries, so web-based
authors take advantage of XML-compatible tagging technology to greatly reduce
their reliance on scripting languages. Due to the custom labeling technology,
Make Web page creators reduce the complexity of making web pages.
(5) Robustness and security:- Because the scripting language used
by JSP pages is the Java language, it has all the benefits of Java technology,
including robust storage management and security.
Disadvantages OF JSP
(1) JSP technology greatly increases the complexity of the product.
In order to gain the cross-platform functionality and product scalability of
the system, the Java system has developed a variety of products, such as Jre, jdk,
j2ee, ejb, jswdk, javabeans, that only effectively combine them together, To
produce a powerful function. (Deployment is difficult)
(2) The efficient operation of Java requires a lot of memory and
hard disk space. On the one hand, Java's high-speed operation is achieved
through the. class file resident memory. On the other hand, hard disk space is
also required to store a series of. java files and. class files, as well as the
corresponding version files. (High hardware requirements)
(3) JSP program debugging difficult:- When the JSP page executes,
it is first converted to a. java file (Servlet), and then the. java file is
compiled into a bytecode file. In this way, the error message actually points
to the converted. java file (Servlet), not the JSP itself. (Debugging is
difficult)
DIFFERENCE BETWEEN JSP AND SERVLET
|
Servlet |
JSP |
|
Servlets are faster as compared to JSP, as they have a short
response time. |
JSP is slower than Servlets, as the first step in the JSP
lifecycle is the conversion of JSP to Java code and then the compilation of
the code. |
|
Servlets are Java-based codes. |
JSP are HTML-based codes. |
|
Servlets are harder to code, as here, the HTML codes are
written in Java. |
JSPs are easier to code, as here Java is
coded in HTML. |
|
In an MVC architecture, Servlets act as the
controllers. |
In MVC architectures, the JSPs act as a view to present the
output to the users. |
|
The service() function can be overridden in Servlets. |
The service() function cannot be overridden in JSPs. |
|
The Servlets are capable of accepting all types of protocol
requests. |
The JSPs are confined to accept only the HTTP
requests. |
|
Modification in Servlets is a time-consuming and challenging
task, as here, one will have to reload, recompile, and then restart the
servers. |
Modification is easy and faster in JSPs as we just need to
refresh the pages. |
|
Servlets require the users to enable the default sessions
management explicitly, as Servlets do not provide default session
management. |
JSPs provide session management by default. |
|
Servlets require us to implement the business logic and
presentation logic in the same servlet file. |
JSPs give us the flexibility to separate the business logic
from the presentation logic using javaBeans. |
|
Servlets can handle extensive data processing. |
JSPs cannot handle data processing functions
efficiently. |
|
Servlets do not provide the facility of writing custom
tags. |
JSPs can provide the facility of building the JSP tags
easily, which can directly call javaBeans. |
|
In Servlets, we do not have implicit objects. |
In JSPs, we have support for implicit objects. |
|
Servlets are hosted and executed on Web Servers. |
JSP is compiled in Java Servlets before their execution.
After that, it has a similar lifecycle as Servlets. |
|
We need to import all the packages at the top of the
Servlets. |
In JSPs, we can import packages anywhere in the file. |
WHAT IS PHP:-
The full form of PHP
is Hypertext Preprocessor. It was abbreviated previously as Personal Home Page.
It is a programming language widely used to build web applications or websites
Rasmus Lerdorf
unleashed the first version of PHP way back in 1994.
HOW TO DOWNLOAD AND
INSTALLED IN PC TO PHP
STEPS:
1.. OPEN GOOGLE,
2.. WRITE IN BROWSER XAMPP
(FULL FORM OF XAMPP is Cross-platform,
Apache, Mysql, Php, and Perl.`) DOWNLOAD, DOWNLOAD FOR WINDOWS OF 64 BIT
NOW AFTER DOWNLOAD, CREATE A
FOLDER IN C: DRIVE FOR INSTALLATION
FOLDER NAME MUST BE ONLY XAMPP
3.. NOW CLICK ON DOWNLOADED
XAMPP FILE, AND DURING INSTALLATION SELECT FOLDER NAME WHICH IS ALREADY CREATED
XAMPP FOLDER
4.. AFTER XAMPP INSTALLED GOTO
C: DRIVE AND OPEN XAMPP FOLDER AND SEARCH XAXMPP_CONTROL ICON AND DOUBLE CLICK
ON THAT ICON, AFTER OPEN XAMPP_CONTROL A POP-UP MESSAGE WILL DISPLAY.
NOW HERE SO MANY OPTION WILL DISPLAY BUT WE WILL START ONLY
TWO OPTION
(1).. APACHE SERVER
(2) MY SQL SERVER, CLICK ON
BOTH START OPTION , THAN QUIT BY QUIT OPTION
5.. OPEN ANY BROWSER AND WRITE
localhost/dashboard/ IN ADDRESS BAR FOR CHECKING , THE BROWSER IS WORKING OR
NOT, IF XAMPP IS INSTALLED A MESSAGE WILL DISPLAY ON THE SCREEN LIKE XAMPP Apache
+ MariaDB + PHP + Perl. MEANS XAMPP IS INSTALLED.
NOW THE XAMPP IS INSTALLED
V.V.V.I NOTE : BEFORE
STARTING THE PHP PROGRAM YOU MUST START THE
XAMPP SERVER, (EVERYDAY COMPUTER SHUTDOWN HONE KE BAD XAMPP AUTOMATIC
CLOSE HOJATA HAI, SO BEFORE STATING THE PHP PROGRAM MUST BE RESTART THE XAMPP
CONTROL, THAN APACHE START )
HOW TO MAKE A PROGRAM
IN PHP
STEPS
1. BE REMEMBER ALL FILES OF PHP WILL STORE IN A SINGLE FOLDER
THAT IS CALLED htdocs FOLDER AND UNDER htdocs FOLDER TO MAKE YOUR OWN FOLDER
like ajay_folder
2. ALWAYS 1ST FILE NAME OF PHP MUST BE index . php, (Har project
ka 1st file name index . php hi hona chahiye otherwise php file run nahi
karega) BECAUSE ONLY index . php WILL
UPLOAD IN BROWSER.
3. NOW OPEN INDEX . PHP
FILE AND WRITE THE CODE OF PHP
SIMPLE PROGRAM 1ST PHP PROGRAM
WAP IN PHP TO DISPLAY YOUR NAME
SOLUTION:
STEPS
1. OPEN NOTE PAD OR ANY OTHER EDITOR
2. WRITE PHP CODE LIKE
<? Php
echo “MY NAME IS AJAY KUMAR
PATHAK”;
?>
(Note: all php code must be
write under the <?php ?>
block only, if you will write out side
the php block than all the statements will be treat as a html statements .)
NOW SAVE THE FIE index . php in
c:\XAMPP\htdocs\ajay_folder\index . php
3. NOW RUN THE PHP FILE
GOTO ANY BROWSER AND WRITE
localhost/ajay_folder/index.php
OUTPUT
INTRODUCTION
OF PHP
:- Rasmus Lerdorf unleashed the first version of PHP way back in 1994.The full
form of PHP is Hypertext Preprocessor. It was abbreviated previously as
Personal Home Page
PHP is an
open-source, server-side programming language that can be used to create
websites, applications, customer relationship management systems and more.
PHP is a server
side scripting language that is embedded in HTML. It is used to manage dynamic
content, databases, session tracking, even build entire e-commerce sites.
It is integrated
with a number of popular databases, including MySQL, PostgreSQL, Oracle,
Sybase, Informix, and Microsoft SQL Server.
PHP when
compiled as an Apache module on the Unix side. The MySQL server, once started,
executes even very complex queries with huge result sets in record-setting
time.PHP Syntax is C-Like.
NOTE : PHP Comments
PHP supports Single
line and Multiline comments. These comments are similar to C/C++ and Perl style
(Unix shell style) comments.
(1).. PHP Single
Line Comments
// (C++ style
single line comment)
# (Unix Shell
style single line comment)
EXAMPLE
<?php
// this is C++
style single line comment
# this is Unix
Shell style single line comment
echo
"Welcome to PHP single line comments";
?>
(2).. PHP Multi Line Comments: We need to enclose all
lines within /* */.
EXAMPLE :
<?php
/*
Anything placed
within comment
will not be
displayed
on the browser;
*/
echo
"Welcome to PHP multi line comment";
?>
2ND
PROGRAM OF PHP (FILE MUST BE SAVE ONLY FILENAME . PHP)
"Hello
World" Script in PHP
To get a feel
for PHP, first start with simple PHP scripts. Since "Hello, World!"
is an essential example, first we will create a friendly little "Hello,
World!" script.
Live Demo
<html>
<head>
<title>Hello
World</title>
</head>
<body>
<?php echo
"Hello, World!";?>
</body>
</html>
OUTPUT
Hello, World!
Q1: WAP IN PHP SWAP TWO NUMBERS
USING A THIRD VARIABLE.
SOLUTION
CODE OF THE PHP
<?php
// Declaring both the numbers
$num1 = 100;
$num2 = 200;
print
("Number 1 original: " . $num1 . "</br>");
print
("Number 2 original: " . $num2 . "</br>");
// Assigning num1 value to temp variable
$temp_num =
$num1;
// Assigning num1 value to num2
$num1 = $num2;
// Assigning num2 value to temp num
$num2 =
$temp_num;
print
("Number 1 modified: " . $num1 . "</br>");
print
("Number 2 modified: " . $num2 . "</br>");
?>
THE END
Q2:WAP IN PHP SWAP TWO NUMBERS , SWAP TWO VARIABLES VALUE WITHOUT USING A
THIRD VARIABLE.
SOLUTION CODE OF
THE PHP
<?php
$a = 5;
$b = 10;
echo
"\nBefore swapping: ". $a .
',' . $b; # 1ST COMMENT LINE #
list($a, $b) =
array($b, $a); //2ND COMMENT LINE,
LIST IS THE COMMAND IT IS ONE COMMENT//
echo
"\nAfter swapping: ". $a . ','
. $b."\n"; /* MULTIPLE COMMENT LINES */
?>
THE END
Q3.
WAP IN PHP , INPUT TWO NUMBERS FROM USER AND FIND THE SUM (SUING HTML AND PHP
CODE)
SAVE AS
FILENAME.HTML
<html>
<body>
<form action
=”abcphp.php” method =”get”>
Number 1 :
<br>
<input name
=”num1”><br><br>
Number 2:
<br>
<input name
=”num2”><br><br><br>
<button type
=”submit”> sum </button>
</form>
</body>
</html>
NOW
PHP PROGRAM I HAVE GIVEN PHP FILE NAME
abcphp.php
<?
<?
$a=$_GET[‘num1’];
$b=$_GET[‘num2’];
echo “Sum of two number =: “.$a+$b; ?>// In place of comma (, operator) We can also
give dot (. operator)?>
THE END
WHAT
IS THE USES / ADVANTAGES OF PHP EXPLAIN IN DETAILS?
PHP (Hypertext Preprocessor) is a widely-used server-side scripting language primarily designed for web development but can also be used for general-purpose programming. It has a variety of uses and applications in web development and beyond. Here, I will explain some of the main uses of PHP in detail:
(1).. Web
Development: Dynamic Web Pages: PHP is often used to create dynamic web pages.
It can generate HTML, JavaScript, CSS, and other web content on the
server-side, which allows for dynamic content generation based on user input or
other data sources.
(2). Server-Side
Scripting: PHP is a server-side scripting language, which means it runs on the
web server rather than the user's browser. It processes requests, interacts
with databases, and generates dynamic web pages before sending them to the
client's browser.
(3). Database
Interaction: PHP can easily connect to various database systems like MySQL,
PostgreSQL, SQLite, and more. It allows for the retrieval, manipulation, and
storage of data in databases, making it a fundamental component of many web
applications.
(4). User
Authentication: PHP can handle user authentication and session (time
limitation) management, allowing developers to create secure (safe) login
systems and restrict access to certain parts of a website.
(5). Form
Handling: It is commonly used to process form data submitted by users. PHP can
validate input, store it in a database, and generate responses based on the
submitted data.
(6). Content
Management Systems (CMS): Many popular CMS platforms like WordPress, Joomla (it
is also called Content Management Systems (CMS), and Drupal (The name Drupal
represents an English rendering of the Dutch word druppel, which means
"drop" (as in a water droplet). The name came from the now-defunct
Drop.org, whose code slowly evolved into Drupal.) are built using PHP. It
enables the creation of customizable and extensible websites and blogs.
(7), Command-Line
Scripting:PHP is not limited to web development. It can be used for writing
command-line scripts to automate tasks, perform system operations, or interact
with files and directories on a server.
(8) API
Development:PHP can be used to create APIs (Application Programming
Interfaces), which allow web applications to communicate with each other or
with mobile apps. It's a versatile language for building server-side APIs that
can deliver data in various formats like JSON (JavaScript Object Notation )or
XML
(9) Web
Services:PHP can consume and provide web services using protocols such as SOAP
(Simple Object Access Protocol) or REST
( Representational State Transfer ). This is useful for integrating with
third-party services and exchanging data between different systems.
(10) Image
Processing and Manipulation:PHP provides libraries and functions for image
manipulation, making it useful for tasks like resizing images, creating
thumbnails, or adding watermarks.
(11) File
Handling:PHP can read and write files on the server, which is essential for
tasks like reading configuration files, managing logs, or uploading and
downloading files.
(12) E-commerce:Many
e-commerce platforms and online shopping carts (a four-wheeled cart provided by
a supermarke) are built using PHP. It
enables the creation of dynamic product catalogs, shopping carts, and secure
payment processing.
(13) Content
Generation:PHP can be used to generate content on the fly, such as creating
dynamic PDF documents, generating XML or CSV (Comma Separated Values ) files, or producing custom reports.
Real-Time
Applications:
(14)PHP can be
combined with technologies like WebSockets to create real-time web
applications, chat applications, or online gaming platforms.
(15) Cross-Platform
Compatibility:PHP can run on various operating systems (Windows, Linux, macOS)
and can be deployed on multiple web servers (Apache, Nginx, etc.), making it
versatile and compatible.
CHARACTERISTICS
OF PHP
1. Familiarity :
The PHP programming language will be familiar to programmers from a variety of
backgrounds. Many of the language's constructs are derived from C and Perl, and
PHP code is frequently indistinguishable from that found in a typical C or
Pascal program. This significantly reduces the learning curve.
2.. Simplicity :
A PHP script can be 10,000 lines long or one line long: whatever you need to
get the job done. There is no need for libraries, special compilation
directives, or anything else. After the first escape sequence (? ), the PHP
engine simply starts executing the code and continues until it reaches the
closing escape sequence (?>). The code will be executed exactly as it is
displayed if it is syntactically correct.
3. Efficiency :
Working in a multipurpose environment such as the WWW necessitates a high level
of efficiency. In addition to session management features, PHP 4.0 introduced a
resource allocation mechanism and more pronounced support for object-oriented
programming. The latest version also includes reference counting, which
eliminates unnecessary memory allocation.
4. Security :
PHP offers developers and administrators a versatile and effective set of
security safeguards.
These safeguards
are classified into two categories:
System level and
application level.
System-Level
Security Safeguards.
5.. Application-Level
Security Safeguard : PHP's pre-defined function set includes several trusted
data encryption options. PHP is also compatible (friendly) with a wide range of
third-party applications, making it simple to integrate with secure e-commerce
technologies. Another benefit is that the PHP source code is not viewable in
the browser because the script is completely parsed before being returned to
the requesting user. This advantage of PHP's server-side architecture prevents
the loss of creative scripts to users who are at least competent enough to
execute a 'View Source' command.
6.. Flexibility
: PHP is an embedded language, so it is extremely adaptable to the needs of the
developer. Although PHP is commonly associated with HTML, it can also be used
in conjunction with languages such as JavaScript, XML, and many others.
Furthermore, as with most other popular programming languages, well-planned PHP
applications can be easily expanded as needed.
7. It's
Open-source: Meaning free to use. It doesn't matter if you're a part-time
developer or a large company with locations around the world. Because PHP is
open-source, you can save a lot of money and use it where it is most needed.
DISADVANTAGE
OF PHP
1.. Security
vulnerabilities – PHP is that it can be weak to security threats if not properly secured.
This is because PHP is an open-source language, meaning that anyone can access
and modify its code. This can leave websites and applications built with PHP
open to attacks from hackers.
2. Inconsistent
coding standards – PHP is that it has inconsistent coding standards, which can
make it difficult for developers to maintain and collaborate on code. This can
lead to errors and inconsistencies in the code, which can be time-consuming to
correct.
3. Limited support
for multithreading – PHP has limited support for multithreading, which can make
it difficult to build applications that require high levels of concurrency.
This can be a disadvantage for applications that need to handle a large number
of simultaneous requests or tasks.
4. Limited
support for object-oriented programming – PHP has limited support for
object-oriented programming (OOP), which can make it difficult to build complex
applications that require advanced OOP features. This can be a disadvantage for
developers who are used to working with other languages that have more robust
OOP capabilities.
5. Limited
performance for certain tasks – While PHP is a high-performance language for
web development, it can have limited performance for certain tasks, such as
image processing or machine learning. This can be a disadvantage for
applications that require these types of tasks to be performed at scale.
WHAT ARE OPERATORS
IN PHP:-
PHP Operator is a symbol
i.e used to perform operations on operands. In simple words, operators are used
to perform operations on variables or values.
For example:
$num=10+20;//+ is the
operator and 10,20 are operands
THE FOLLOWING
LISTS DESCRIBE THE DIFFERENT OPERATORS USED IN PHP.
1.. Arithmetic Operators
2. Assignment Operators
3. Bitwise Operators
4. Comparison Operators
5. Incrementing/Decrementing Operators
6. Logical Operators .
7 String Operators .
8 Array Operators
9. Conditional or Ternary Operators.
10. Spaceship Operators.
(1).. Arithmetic
Operators : The PHP arithmetic operators
are used to perform common arithmetic operations such as addition, subtraction,
etc. with numeric values.
|
Operator |
Name |
Example |
Explanation |
|
+ |
Addition |
$a + $b |
Sum of operands |
|
- |
Subtraction |
$a - $b |
Difference of operands |
|
* |
Multiplication |
$a * $b |
Product of operands |
|
/ |
Division |
$a / $b |
Quotient of operands |
|
% |
Modulus |
$a % $b |
Remainder of operands |
|
** |
Exponentiation |
$a ** $b |
$a raised to the power $b |
(2).. Assignment Operators : The assignment operators are used to assign value to different variables.
The
basic assignment operator is "=".
|
Operator |
Name |
Example |
Explanation |
|
= |
Assign |
$a = $b |
The value of right operand is assigned to
the left operand. |
|
+= |
Add then Assign |
$a += $b |
Addition same as $a = $a + $b |
|
-= |
Subtract then Assign |
$a -= $b |
Subtraction same as $a = $a - $b |
|
*= |
Multiply then Assign |
$a *= $b |
Multiplication same as $a = $a * $b |
|
/= |
Divide then Assign |
$a /= $b |
Find quotient same as $a = $a / $b |
|
%= |
Divide then Assign |
$a %= $b |
Find remainder same
as $a = $a % $b |
(3).. Bitwise Operators :
The bitwise operators are used to perform bit-level operations on operands.
These operators allow the evaluation and manipulation of specific bits within
the integer
|
Operator |
Name |
Example |
Explanation |
|
& |
And |
$a & $b |
Bits that are 1 in both $a and $b are set to
1, otherwise 0. |
|
| |
Or (Inclusive or) |
$a | $b |
Bits that are 1 in either $a or $b are set
to 1 |
|
^ |
Xor (Exclusive or) |
$a ^ $b |
Bits that are 1 in either $a or $b are set
to 0. |
|
~ |
Not |
~$a |
Bits that are 1 set to 0 and bits that are 0
are set to 1 |
|
<< |
Shift left |
$a << $b |
Left shift the bits of operand $a $b steps |
|
>> |
Shift right |
$a >> $b |
Right shift the bits of $a operand by $b
number of places |
|
Operator |
Name |
Example |
Explanation |
|
== |
Equal |
$a == $b |
Return TRUE if $a is equal to $b |
|
=== |
Identical |
$a === $b |
Return TRUE if $a is equal to $b, and they
are of same data type |
|
!== |
Not identical |
$a !== $b |
Return TRUE if $a is not equal to $b, and
they are not of same data type |
|
!= |
Not equal |
$a != $b |
Return TRUE if $a is not equal to $b |
|
<> |
Not equal |
$a <> $b |
Return TRUE if $a is not equal to $b |
|
< |
Less than |
$a < $b |
Return TRUE if $a is less than $b |
|
> |
Greater than |
$a > $b |
Return TRUE if $a is greater than $b |
|
<= |
Less than or equal to |
$a <= $b |
Return TRUE if $a is less than or equal $b |
|
>= |
Greater than or equal to |
$a >= $b |
Return TRUE if $a is greater than or equal
$b |
|
<=> |
Spaceship |
$a <=>$b |
Return -1 if $a is
less than $b |
(5).. Incrementing/Decrementing
Operators :
The increment and decrement operators are used to increase
and decrease the value of a variable.
|
Operator |
Name |
Example |
Explanation |
|
++ |
Increment |
++$a |
Increment the value of $a by one, then return
$a |
|
$a++ |
Return $a, then increment the value of $a by
one |
||
|
-- |
decrement |
--$a |
Decrement the value of $a by one, then
return $a |
|
$a-- |
Return $a, then decrement the value of $a by
one |
(6).. Logical or Relational
Operators: The logical operators are used to perform bit-level
operations on operands. These operators allow the evaluation and manipulation
of specific bits within the integer.
|
Operator |
Name |
Example |
Explanation |
|
and |
and |
$a and $b |
Return TRUE if both $a and $b are true |
|
or |
or |
$a or $b |
Return TRUE if either $a or $b is true |
|
xor |
xor |
$a xor $b |
Return TRUE if either $ or $b is true but
not both |
|
! |
not |
! $a |
Return TRUE if $a is not true |
|
&& |
and |
$a && $b |
Return TRUE if either $a and $b are true |
|
|| |
or |
$a || $b |
Return TRUE if either $a or $b is true |
(7).. String Operators : The string operators are used to perform the operation on strings.
There are two
string operators in PHP.
|
Operator |
Name |
Example |
Explanation |
|
. |
Concatenation |
$a . $b |
Concatenate both $a and $b |
|
.= |
Concatenation and Assignment |
$a .= $b |
First concatenate $a and $b, then assign the
concatenated string to $a, e.g. $a = $a . $b |
(8) Array Operators : The
array operators are used in case of array. Basically, these operators are used
to compare the values of arrays.
|
Operator |
Name |
Example |
Explanation |
|
+ |
Union |
$a + $y |
Union of $a and $b |
|
== |
Equality |
$a == $b |
Return TRUE if $a and $b have same key/value
pair |
|
!= |
Inequality |
$a != $b |
Return TRUE if $a is not equal to $b |
|
=== |
Identity |
$a=== $b |
Return TRUE if $a and $b have same key/value
pair of same type in same order (Returns True if both the operands are equal
and are of the same type) |
|
!== |
Non-Identity |
$a!== $b |
Return TRUE if $a is not identical to $b |
|
<> |
Inequality |
$a <> $b |
Return TRUE if $a is not equal to $b |
(9).. Conditional or Ternary Operators: These operators are used to compare two values and take either of the results simultaneously, depending on whether the outcome is TRUE or FALSE.
Example : $var = (condition)? value1 : value2;
Operator
|
Name
|
Operation
|
|
?: |
Ternary |
If the condition
is true? then $x : or else $y. This means that if the condition is true then
the left result of the colon is accepted otherwise the result is on right. |
10. Spaceship
Operators. PHP 7 has introduced a new kind of operator called spaceship
operator. The spaceship operator or combined comparison operator is denoted by
“<=>“. These operators are used to compare values but instead of
returning the boolean results, it returns integer values. If both the operands
are equal, it returns 0. If the right operand is greater, it returns -1. If the
left operand is greater, it returns 1. The following table shows how it works
in detail:
Example
<?php
$x = 500;
$y = 500;
$z = 250;
echo $x <=> $y;
echo "\n";
echo $x <=> $z;
echo "\n";
echo $z <=> $y;
echo "\n";
// We can do the same for Strings
$x = "Ajay";
$y = "Pathak";
echo $x <=> $y;
echo "\n";
echo $x <=> $y;
echo "\n";
echo $y <=> $x;
?>
OUTPUT
0
1
-1
1
1
-1
Spaceship Operators:-
Operator
|
Syntax
|
Operation
|
|
$x <
$y |
$x
<=> $y |
Identical to -1 (right is greater) |
|
$x >
$y |
$x
<=> $y |
Identical to 1 (left is greater) |
|
$x
<= $y |
$x
<=> $y |
Identical to -1 (right is greater) or
identical to 0 (if both are equal) |
|
$x
>= $y |
$x
<=> $y |
Identical to 1 (if left is greater) or
identical to 0 (if both are equal) |
|
$x ==
$y |
$x
<=> $y |
Identical to 0 (both are equal) |
|
$x !=
$y |
$x
<=> $y |
Not Identical to 0 |
FLOW CONTROL IN PHP :
The Flow Control Statements in PHP change the flow of
execution of statements, and if other statements get executed are determined by
these statements. The flow of the program is from top to bottom, but what if we
want to execute a snippet of code when the condition satisfies?
There are several types of flow control structures in PHP:
an if statement looks like:
if: Allows you to execute code block only if a specified
condition is true.
else: Used with an if statement to execute a block of code
when the condition is false.
elseif: Allows you to test multiple conditions in
sequence.
switch: Used to select one of many code blocks to be
executed based on the value of an expression.
Looping Statements:
for: Executes a block of code a specified number of times.
while: Repeats a block of code as long as a specified
condition is true.
do...while: Similar to while, but it guarantees that the
code block is executed at least once.
foreach: Iterates over elements in an array or other
iterable data structures.
Example of a for loop
(1).. CONDITIONAL STATEMENTS:
If : The if statement checks the truthfulness of an
expression and, if the expression is true, evaluates a statemen
EXAMPLE:
<?php
$number = 10;
if ($number > 5) {
echo "The
number is greater than 5";
}
?>
EXAMPLE: IF ELSE
<?php
$age = 18;
if ($age >= 18) {
echo "You are
eligible to vote.";
} else {
echo "You are
not eligible to vote.";
}
?>
EXAMPLE : IF ELSE IF
<?php
$score = 75;
if ($score >= 90) {
echo "Your
grade is A";
} else if ($score >= 80) {
echo "Your
grade is B";
} else if ($score >= 70) {
echo "Your
grade is C";
} else if ($score >= 60) {
echo "Your
grade is D";
} else {
echo "Your
grade is F";
}
?>
EXAMPLE OF A SWITCH CASE STATEMENT
IN PHP:
$color = "red";
switch ($color) {
case
"red":
echo
"The color is red.";
break;
case
"green":
echo
"The color is green.";
break;
case
"blue":
echo
"The color is blue.";
break;
default:
echo
"The color is unknown.";
break;
}
FOR LOOPS IN PHP:
for ($i = 1; $i <= 10; $i++) {
echo $i .
"\n";
}
NESTED FOR LOOP
<?php
$array1 = array("apple", "banana",
"orange");
$array2 = array("red", "yellow",
"orange");
for ($i = 0; $i < count($array1); $i++) {
for ($j = 0; $j
< count($array2); $j++) {
echo
$array1[$i] . " is " . $array2[$j] . "<br>";
}
}
?>
WHILE LOOP:
$num = 1;
while ($num <= 5) {
echo $num .
" ";
$num++;
}
DO WHILE LOOP
$num = 1;
do {
echo $num;
$num++;
} while ($num <= 5);
THE PHP FOREACH LOOP:
The foreach loop works only on arrays, and is used to loop
through each key/value pair in an array.
Syntax
foreach ($array as $value) {
code to be
executed;
}
EXAMPLE OF FOREACH LOOP
<!DOCTYPE html>
<html>
<body>
<?php
$name = array("ajay", "anil",
"rakesh", "sanjeev");
foreach ($name as $value) {
echo "$value
<br>";
}
?>
</body>
</html>
2nd EXAMPLE OF FOREACH
LOOP
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value
* 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last
element
?>
PROGRAM FOR PRACTICAL IN PHP
WAP IN PHP INPUT A NUMBER AND CHECK THE ENTERED NUMBER IS ARMSTRONG OR NOT (OK)
SAVE AS FILENAME.PHP
<html>
<body>
<form method="post">
Enter the
Number:
<input type="number"
name="number">
<input type="submit"
value="Submit">
</form>
</body>
</html>
<?php
if($_POST)
{
//get the number
entered
$number =
$_POST['number'];
//store entered
number in a variable
$a = $number;
$sum = 0;
//run loop till
the quotient is 0
while( $a != 0
)
{
$rem = $a % 10; //find reminder
$sum = $sum + ( $rem * $rem * $rem ); //cube the
reminder and add it to the sum variable till the loop ends
$a = $a / 10; //find quotient. if 0 then loop
again
}
//if the entered
number and $sum value matches then it is an armstrong number
if( $number ==
$sum )
{
echo "Yes
$number an Armstrong Number";
}else
{
echo
"$number is not an Armstrong Number";
}
}
?>
WHAT IS STRING IN PHP:
In PHP, a string is a data type used to represent text. It
can contain a sequence of characters, such as letters, numbers, symbols, and
spaces. Strings are one of the most commonly used data types in PHP, and they
can be manipulated and processed in various ways.
Creating a String:
There are 4 ways to specify a string literal in PHP.
(1)..single quoted : Example
<?php
$str='I am
using single quoted, Hello text within single quote';
echo
$str;
?>
(2).. double quoted : Example
<?php
$str="Hello text within double quote";
echo $str;
?>
(3)..heredoc syntax :
Heredoc: Heredoc syntax (<<<) is the third way to
delimit strings. In Heredoc syntax, an identifier is provided after this
heredoc <<< operator, and immediately a new line is started to write
any text. To close the quotation, the string follows itself and then again that
same identifier is provided. That closing identifier must begin from the new
line without any whitespace or tab.
Naming Rules
The identifier should follow the naming rule that it must
contain only alphanumeric characters and underscores, and must start with an
underscore or a non-digit character.
For Example
Valid Example
<?php
$str =
<<<Demo
It is a valid example
Demo; //Valid
code as whitespace or tab is not valid before closing identifier
echo $str;
?>
Invalid Example
We cannot use any whitespace or tab before and after the
identifier and semicolon, which means identifier must not be indented. The
identifier must begin from the new line.
<?php
$str =
<<<Demo
It is Invalid example
Demo;
//Invalid code as whitespace or tab is not valid before closing
identifier
echo $str;
?>
(4)..newdoc syntax (since PHP 5.3):
Newdoc is similar to the heredoc, but in newdoc parsing is
not done. It is also identified with three less than symbols <<<
followed by an identifier. But here identifier is enclosed in single-quote,
e.g. <<<'EXP'. Newdoc follows the same rule as heredocs.
Example:
$str =
<<<'DEMO'
Welcome to
javaTpoint.
Learn
with newdoc example.
DEMO;
echo $str;
echo '</br>';
Welcome to javaTpoint.
Learn
with newdoc example.
Demo;
?>
INVALID EXAMPLE
We cannot use any whitespace or tab before and after the
identifier and semicolon, means identifier must not be indented. The identifier
must begin from the new line. It is also invalid in newdoc same as heredoc.
<?php
$str =
<<<'Demo'
It is Invalid example
Demo; //Invalid
code as whitespace or tab is not valid before closing identifier
echo $str;
?>
THE END
PHP ARRAYS :
An
array is the data structure that allows the storage of multiple values under a
single name. In simple terms, it’s a variable that is capable of containing
more than one values. The values assigned to the array are homogeneous in
nature, it means the data type of all the values should be the same. If an
array is supposed to be containing the integer value only then it won’t be
possible to store character or string values in that.
An
array could also be considered a collection of items which follows a specific
order to store the items or values. Once the array is created, we can assign
several values to it.
TYPES OF ARRAY
There are basically three types of arrays in PHP:
(1).. INDEXED OR NUMERIC ARRAYS:
An array with a numeric index where values are stored linearly.
These type of arrays can be used to store any type of
elements, but an index is always a number. By default, the index starts at
zero. These arrays can be created in two different ways.
EXAMPLE : SAVE AS FILENAME.PHP
<?php
// 1st
One way to create an indexed array
$name_one = array("AJAY", "SHIVA",
"ANURAG", "AKASH", "Raghav"); // HERE IF I AM NOT
DEFINING INDEX NO (LIKE 0,1,2,3 ETC) THAN AUTOMATICALLY CREATED INDEX ARRAY AND
START ALWAYS FROM 0 (ZERO)
print_r($name_one); // THROUGH THIS COMMAND WE CAN SEE THE
STRUCTURE OF ARRAY, IT IS OPTIONAL
// Accessing the elements directly
echo "Accessing the 1st array elements
directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
// 2nd Second way to create an indexed array
$name_two[0] = "AJAY";
$name_two[1] = "SHIVA";
$name_two[2] = "ANURAG";
$name_two[3] = "AKASH";
$name_two[4] = "RAGHAV";
// Accessing the elements directly
echo "Accessing the 2nd array elements
directly:\n";
echo $name_two[2], "\n";
echo $name_two[0], "\n";
echo $name_two[4], "\n";
?>
(2).. ASSOCIATIVE ARRAYS:
An array with a string index where instead of linear storage, each value can be
assigned a specific key.
These types of arrays are similar to the indexed arrays
but instead of linear storage, every value can be assigned with a user-defined
key of string type.
EXAMPLE : SAVE AS FILENAME.PHP
<?php
// 1ST One way to create an associative array
$name_one = array("Zack"=>"Zara",
"Anthony"=>"Any",
"Ram"=>"Rani",
"Salim"=>"Sara",
"Raghav"=>"Ravina");
// => THIS SIGN IS CALLED KEY HERE ZACK IS KEY WORD BUT KEY IS INDICATING BY
=> SIGN AND ZARA IS THE VALUES OF ZACK, SAME AS ANTHONY IS KEY WORD AND ANY
IS THE VALUE OF ANTHONY , SAME AS RAM IS KEY WORD AND RANI IS THE VALUE OF RAM
, ETC.
// 2ND Second way to create an associative
array
$name_two["zack"] = "zara";
$name_two["anthony"] = "any";
$name_two["ram"] = "rani";
$name_two["salim"] = "sara";
$name_two["raghav"] = "ravina";
// Accessing the elements directly
echo "Accessing the elements directly:\n";
echo $name_two["zack"], "\n";
echo $name_two["salim"], "\n";
echo $name_two["anthony"], "\n";
echo $name_one["Ram"], "\n";
echo $name_one["Raghav"], "\n";
?>
(3).. MULTIDIMENSIONAL ARRAYS:
An array which contains single or multiple array within it and can be accessed
via multiple indices.
Multi-dimensional arrays are such arrays that store
another array at each index instead of a single element. We can define
multi-dimensional arrays as an array of arrays. As the name suggests, every
element in this array can be an array and they can also hold other sub-arrays
within. Arrays or sub-arrays in multidimensional arrays can be accessed using
multiple dimensions.
EXAMPLE:
<?php
// Defining a multidimensional array
$favorites = array(
array(
"name"
=> "Dave Punk",
"mob"
=> "5689741523",
"email"
=> "davepunk@gmail.com",
),
array(
"name"
=> "Monty Smith",
"mob"
=> "2584369721",
"email"
=> "montysmith@gmail.com",
),
array(
"name"
=> "John Flinch",
"mob"
=> "9875147536",
"email"
=> "johnflinch@gmail.com",
)
);
// Accessing elements
echo "Dave Punk email-id is: " .
$favorites[0]["email"], "\n";
echo "John Flinch mobile number is: " .
$favorites[2]["mob"];
?>
THE END UNIT 5 (JAVA
SCRIPT)
No comments:
Post a Comment
PLEASE DO LEAVE YOUR COMMENTS